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): switch batch trace summarization to gpt-5-nano on flex (#91639)

Bernat Torres27f022b98c9f
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index cb0e6f6498e0..61da9f697da7 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -25,6 +25,9 @@ MAX_CONCURRENT_WORKFLOW_TASKS: int | None = get_from_env(
"MAX_CONCURRENT_WORKFLOW_TASKS", None, optional=True, type_cast=int
)
MAX_CONCURRENT_ACTIVITIES: int | None = get_from_env("MAX_CONCURRENT_ACTIVITIES", None, optional=True, type_cast=int)
+# Batch trace summarization model; overridable so a fleet-wide model rollback is a config change
+# plus a worker restart, not a deploy.
+LLMA_SUMMARIZATION_MODEL: str = get_from_env("LLMA_SUMMARIZATION_MODEL", "gpt-5-nano")
TARGET_MEMORY_USAGE: float | None = get_from_env("TARGET_MEMORY_USAGE", None, optional=True, type_cast=float)
TARGET_CPU_USAGE: float | None = get_from_env("TARGET_CPU_USAGE", None, optional=True, type_cast=float)
diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.md
index c59ebc9eaa3a..438524362da9 100644
--- a/posthog/temporal/ai_observability/trace_summarization/README.md
+++ b/posthog/temporal/ai_observability/trace_summarization/README.md
@@ -136,21 +136,21 @@ Teams are discovered dynamically via `team_discovery.py`. Guaranteed teams (in `
Key constants in `constants.py`:
-| Constant | Default | Description |
-| ------------------------------------------- | -------------- | ----------------------------------------------- |
-| `DEFAULT_MAX_ITEMS_PER_WINDOW` | 15 | Max items per window |
-| `DEFAULT_BATCH_SIZE` | 5 | Concurrent item processing |
-| `DEFAULT_MAX_CONCURRENT_TEAMS` | 20 | Max teams to process in parallel |
-| `DEFAULT_MODE` | "detailed" | Summary detail level |
-| `DEFAULT_MODEL` | "gpt-4.1-nano" | LLM model for summarization |
-| `DEFAULT_WINDOW_MINUTES` | 60 | Time window to query |
-| `WORKFLOW_EXECUTION_TIMEOUT_MINUTES` | 30 | Max per-team workflow duration |
-| `COORDINATOR_EXECUTION_TIMEOUT_MINUTES` | 55 | Max coordinator workflow duration |
-| `SAMPLE_TIMEOUT_SECONDS` | 900 | Sampling activity timeout (per attempt) |
-| `FETCH_AND_FORMAT_START_TO_CLOSE_TIMEOUT` | 120s | Fetch + format activity timeout (per attempt) |
-| `FETCH_AND_FORMAT_HEARTBEAT_TIMEOUT` | 60s | Heartbeat window for fetch activity |
-| `SUMMARIZE_AND_SAVE_START_TO_CLOSE_TIMEOUT` | 900s | Summarize + save activity timeout (per attempt) |
-| `SUMMARIZE_AND_SAVE_HEARTBEAT_TIMEOUT` | 60s | Heartbeat window for summarize activity |
+| Constant | Default | Description |
+| ------------------------------------------- | ------------ | ----------------------------------------------- |
+| `DEFAULT_MAX_ITEMS_PER_WINDOW` | 15 | Max items per window |
+| `DEFAULT_BATCH_SIZE` | 5 | Concurrent item processing |
+| `DEFAULT_MAX_CONCURRENT_TEAMS` | 20 | Max teams to process in parallel |
+| `DEFAULT_MODE` | "detailed" | Summary detail level |
+| `DEFAULT_MODEL` | "gpt-5-nano" | LLM model for summarization (flex service tier) |
+| `DEFAULT_WINDOW_MINUTES` | 60 | Time window to query |
+| `WORKFLOW_EXECUTION_TIMEOUT_MINUTES` | 30 | Max per-team workflow duration |
+| `COORDINATOR_EXECUTION_TIMEOUT_MINUTES` | 55 | Max coordinator workflow duration |
+| `SAMPLE_TIMEOUT_SECONDS` | 900 | Sampling activity timeout (per attempt) |
+| `FETCH_AND_FORMAT_START_TO_CLOSE_TIMEOUT` | 120s | Fetch + format activity timeout (per attempt) |
+| `FETCH_AND_FORMAT_HEARTBEAT_TIMEOUT` | 60s | Heartbeat window for fetch activity |
+| `SUMMARIZE_AND_SAVE_START_TO_CLOSE_TIMEOUT` | 900s | Summarize + save activity timeout (per attempt) |
+| `SUMMARIZE_AND_SAVE_HEARTBEAT_TIMEOUT` | 60s | Heartbeat window for summarize activity |
Retry policies: `SAMPLE_RETRY_POLICY` (5 attempts with backoff), `FETCH_AND_FORMAT_RETRY_POLICY` (2 attempts), `SUMMARIZE_AND_SAVE_RETRY_POLICY` (2 attempts with backoff, `TextReprExpiredError` non-retryable), `COORDINATOR_CHILD_WORKFLOW_RETRY_POLICY` (1 attempt). All retry policies exclude `ValueError` and `TypeError` from retries.
diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.py
index 06b95a0c024c..01c8d3951526 100644
--- a/posthog/temporal/ai_observability/trace_summarization/constants.py
+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py
@@ -2,6 +2,8 @@
from datetime import timedelta
+from django.conf import settings
+
from temporalio.common import RetryPolicy
from products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationMode
@@ -15,7 +17,11 @@ DEFAULT_TRACE_BATCH_SIZE = 6 # Traces processed in small parallel batches
DEFAULT_MODE = SummarizationMode.DETAILED
DEFAULT_WINDOW_MINUTES = 60 # Process traces from last N minutes (matches schedule frequency)
DEFAULT_WINDOW_OFFSET_MINUTES = 30 # Offset window into the past so traces have time to fully complete
-DEFAULT_MODEL = OpenAIModel.GPT_4_1_NANO
+# parse() fails the worker at boot on a value outside OpenAIModel, naming the valid models,
+# instead of failing every summary at runtime. It cannot check the other constraint: the value
+# must also be on the Python gateway's llma_summarization allowlist
+# (services/llm-gateway/src/llm_gateway/products/config.py), or the fallback path 403s.
+DEFAULT_MODEL = OpenAIModel.parse(settings.LLMA_SUMMARIZATION_MODEL)
# Max estimated raw trace size (in characters) before formatting.
# Traces exceeding this are skipped — formatting huge traces is CPU-intensive
diff --git a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
index 80cefb44c4e8..bb1c1e08c7a5 100644
--- a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
+++ b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
@@ -215,6 +215,9 @@ async def summarize_and_save_activity(input: SummarizeAndSaveInput) -> Summariza
mode=mode_enum,
model=model_enum,
user_id=f"temporal-workflow-team-{input.team_id}",
+ # The batch pipeline can wait for its summaries, so it takes the cheaper flex tier.
+ # The provider falls back to the standard tier when flex is refused or stalls.
+ flex=True,
)
llm_duration_s = time.monotonic() - t0
log.info(
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
index 5bb0805152a7..1419088776f9 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
@@ -106,6 +106,8 @@ class TestSummarizeAndSaveActivity:
assert result.trace_id == input_data.trace_id
assert result.generation_id is None
assert result.embedding_requested is True
+ # Dropping flex here silently doubles the pipeline's LLM bill, so pin it.
+ assert mock_summarize.call_args.kwargs["flex"] is True
mock_create_event.assert_called_once()
call_kwargs = mock_create_event.call_args.kwargs
assert call_kwargs["event"] == "$ai_trace_summary"
diff --git a/products/ai_observability/backend/summarization/budget.py b/products/ai_observability/backend/summarization/budget.py
index a81f6336679e..23c930f1bde1 100644
--- a/products/ai_observability/backend/summarization/budget.py
+++ b/products/ai_observability/backend/summarization/budget.py
@@ -12,6 +12,7 @@ MODEL_CONTEXT_TOKENS: dict[str, int] = {
OpenAIModel.GPT_4O_MINI: 128_000,
OpenAIModel.GPT_4O: 128_000,
OpenAIModel.GPT_5_MINI: 400_000,
+ OpenAIModel.GPT_5_NANO: 400_000,
}
# Held back from the window for the system prompt and the model's own response.
diff --git a/products/ai_observability/backend/summarization/constants.py b/products/ai_observability/backend/summarization/constants.py
index ca360275da1f..ea257d6daead 100644
--- a/products/ai_observability/backend/summarization/constants.py
+++ b/products/ai_observability/backend/summarization/constants.py
@@ -8,3 +8,8 @@ DEFAULT_MODE = SummarizationMode.MINIMAL
# Timeout configuration (seconds)
SUMMARIZATION_TIMEOUT = 120
+# Flex requests queue for spare provider capacity, so they get a longer deadline. It must stay
+# under the ai-gateway's buffered-response ceiling: the gateway cuts a non-streaming call at
+# ~290s and answers 504 (DefaultBufferedHeaderTimeout in ai-gateway internal/dispatch/proxy),
+# which the SDK raises as InternalServerError, so the standard-tier fallback still runs.
+SUMMARIZATION_FLEX_TIMEOUT = 180
diff --git a/products/ai_observability/backend/summarization/llm/call.py b/products/ai_observability/backend/summarization/llm/call.py
index 77f23e5ccb75..380bde977b33 100644
--- a/products/ai_observability/backend/summarization/llm/call.py
+++ b/products/ai_observability/backend/summarization/llm/call.py
@@ -18,6 +18,7 @@ def summarize(
mode: SummarizationMode = DEFAULT_MODE,
model: OpenAIModel | None = None,
user_id: str | None = None,
+ flex: bool = False,
) -> SummarizationResponse:
"""
Generate AI-powered summary from text representation via LLM gateway.
@@ -28,9 +29,10 @@ def summarize(
mode: Summary detail level
model: OpenAI model to use (defaults to gpt-4.1-mini)
user_id: Optional user distinct_id for analytics attribution
+ flex: Request the flex service tier, cheaper but slower (gpt-5 family only)
Returns:
Structured summarization response with flow diagram, bullets, and notes
"""
openai_model = cast(OpenAIModel, model) if model else DEFAULT_MODEL_OPENAI
- return summarize_with_openai(text_repr, team_id, mode, openai_model, user_id)
+ return summarize_with_openai(text_repr, team_id, mode, openai_model, user_id, flex=flex)
diff --git a/products/ai_observability/backend/summarization/llm/openai.py b/products/ai_observability/backend/summarization/llm/openai.py
index 0f9f7e464b67..888ccd628b90 100644
--- a/products/ai_observability/backend/summarization/llm/openai.py
+++ b/products/ai_observability/backend/summarization/llm/openai.py
@@ -1,15 +1,16 @@
"""OpenAI provider for LLM summarization, routed through the internal Go ai-gateway
when configured, else the Python LLM gateway."""
-from typing import Any, cast
+from typing import Any, Literal
import structlog
-from openai.types.chat import ChatCompletionMessageParam
+from openai import APIConnectionError, APIError, APIStatusError, InternalServerError, Omit, OpenAI, RateLimitError, omit
+from openai.types.chat import ChatCompletion, ChatCompletionMessageParam
from rest_framework import exceptions
from posthog.llm.gateway_client import build_openai_client, team_distinct_id
-from ..constants import SUMMARIZATION_TIMEOUT
+from ..constants import SUMMARIZATION_FLEX_TIMEOUT, SUMMARIZATION_TIMEOUT
from ..models import OpenAIModel, SummarizationMode
from ..utils import load_summarization_template
from .schema import SummarizationResponse
@@ -17,17 +18,52 @@ from .schema import SummarizationResponse
logger = structlog.get_logger(__name__)
+def _is_gpt5_model(model: OpenAIModel) -> bool:
+ return str(model).startswith("gpt-5")
+
+
+# Deliberately an allowlist rather than the family prefix: OpenAI decides flex eligibility per
+# model (the pro tiers are excluded, for example), so a new gpt-5 entry in OpenAIModel must not
+# inherit the flex tier until someone checks the pricing page and adds it here.
+FLEX_CAPABLE_MODELS: frozenset[OpenAIModel] = frozenset({OpenAIModel.GPT_5_NANO, OpenAIModel.GPT_5_MINI})
+
+
+def _is_flex_recoverable(error: APIError) -> bool:
+ """Whether a failed flex attempt should retry on the standard tier.
+
+ Recoverable: a capacity refusal (429), a connection reset or client timeout
+ (APIConnectionError covers its APITimeoutError subclass), any 5xx (the ai-gateway answers
+ 504 at its buffered-response ceiling), and 408, which OpenAI's flex docs use for a
+ server-side flex timeout and the SDK raises as the bare APIStatusError. Anything else
+ (400 bad request, auth errors) is a configuration problem the standard tier shares, so it
+ propagates instead of masking itself behind a fallback.
+ """
+ if isinstance(error, RateLimitError | APIConnectionError | InternalServerError):
+ return True
+ return isinstance(error, APIStatusError) and error.status_code == 408
+
+
+# Strict json_schema keeps the model's output parseable by SummarizationResponse without a
+# repair step.
+SUMMARIZATION_RESPONSE_FORMAT: Any = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "summarization_response",
+ "strict": True,
+ "schema": SummarizationResponse.model_json_schema(),
+ },
+}
+
+
def summarize_with_openai(
text_repr: str,
team_id: int,
mode: SummarizationMode,
model: OpenAIModel,
user_id: str | None = None,
+ flex: bool = False,
) -> SummarizationResponse:
"""Generate summary using OpenAI API via LLM gateway with structured outputs."""
- system_prompt = load_summarization_template(f"prompts/system_{mode}.djt", {})
- user_prompt = load_summarization_template("prompts/user.djt", {"text_repr": text_repr})
-
resolved_distinct_id = user_id or team_distinct_id(team_id)
client = build_openai_client(
"llma_summarization",
@@ -37,29 +73,66 @@ def summarize_with_openai(
)
messages: list[ChatCompletionMessageParam] = [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
+ {"role": "system", "content": load_summarization_template(f"prompts/system_{mode}.djt", {})},
+ {"role": "user", "content": load_summarization_template("prompts/user.djt", {"text_repr": text_repr})},
]
- try:
- response = client.chat.completions.create(
+ # gpt-5 models spend hidden reasoning tokens that bill as output. Minimal effort removes
+ # them without changing the visible summary volume. Family-wide on purpose, unlike the
+ # flex allowlist: every gpt-5 reasoning model wants minimal effort for this task, and a
+ # new one silently paying reasoning tokens is the costlier default mistake.
+ # Both kwargs go through the SDK's typed signature; `omit` leaves the field out of the
+ # request entirely, where None would send an explicit null.
+ reasoning_effort: Literal["minimal"] | Omit = "minimal" if _is_gpt5_model(model) else omit
+
+ def _create(request_client: OpenAI, service_tier: Literal["flex"] | Omit, timeout: float) -> ChatCompletion:
+ return request_client.chat.completions.create(
model=str(model),
messages=messages,
user=resolved_distinct_id,
- timeout=SUMMARIZATION_TIMEOUT,
- response_format=cast(
- Any,
- {
- "type": "json_schema",
- "json_schema": {
- "name": "summarization_response",
- "strict": True,
- "schema": SummarizationResponse.model_json_schema(),
- },
- },
- ),
+ timeout=timeout,
+ response_format=SUMMARIZATION_RESPONSE_FORMAT,
+ reasoning_effort=reasoning_effort,
+ service_tier=service_tier,
)
+ try:
+ if flex and model in FLEX_CAPABLE_MODELS:
+ fell_back = False
+ try:
+ # max_retries=0: the SDK would otherwise retry the recoverable statuses (408,
+ # 429, 5xx) up to twice against the same starved tier, each attempt getting the
+ # full timeout, and 3 x 180s stacked with the standard attempts below reaches the
+ # summarize activity's 900s start_to_close, cutting the fallback mid-flight.
+ # Failing over immediately bounds the worst case at 180s + 3 x 120s = 540s.
+ response = _create(client.with_options(max_retries=0), "flex", SUMMARIZATION_FLEX_TIMEOUT)
+ except APIError as flex_error:
+ # Flex runs on spare provider capacity, so the attempt can fail in several
+ # documented ways; _is_flex_recoverable names them. Retry once at the standard
+ # tier so the window gets its summary.
+ if not _is_flex_recoverable(flex_error):
+ raise
+ logger.info(
+ "summarization_flex_fell_back",
+ error_type=type(flex_error).__name__,
+ model=str(model),
+ team_id=team_id,
+ )
+ fell_back = True
+ response = _create(client, omit, SUMMARIZATION_TIMEOUT)
+ # The response reports the tier that actually served, so production logs answer the
+ # two open rollout questions on day one: does the gateway forward service_tier, and
+ # how often does flex refuse.
+ logger.info(
+ "summarization_served_tier",
+ service_tier=response.service_tier,
+ fell_back=fell_back,
+ model=str(model),
+ team_id=team_id,
+ )
+ else:
+ response = _create(client, omit, SUMMARIZATION_TIMEOUT)
+
content = response.choices[0].message.content
if not content:
raise exceptions.ValidationError("OpenAI returned empty response")
diff --git a/products/ai_observability/backend/summarization/models.py b/products/ai_observability/backend/summarization/models.py
index f955a92dd3ca..f588b2b07874 100644
--- a/products/ai_observability/backend/summarization/models.py
+++ b/products/ai_observability/backend/summarization/models.py
@@ -11,6 +11,7 @@ class OpenAIModel(StrEnum):
GPT_4O_MINI = "gpt-4o-mini"
GPT_4O = "gpt-4o"
GPT_5_MINI = "gpt-5-mini"
+ GPT_5_NANO = "gpt-5-nano"
@classmethod
def parse(cls, value: str) -> "OpenAIModel":
diff --git a/products/ai_observability/backend/summarization/tests/test_call.py b/products/ai_observability/backend/summarization/tests/test_call.py
index 7bbbf34f5ef5..abe71a791799 100644
--- a/products/ai_observability/backend/summarization/tests/test_call.py
+++ b/products/ai_observability/backend/summarization/tests/test_call.py
@@ -35,6 +35,7 @@ class TestSummarize:
DEFAULT_MODE,
DEFAULT_MODEL_OPENAI,
None,
+ flex=False,
)
assert result == mock_response
diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.py
index a7c4d3434032..b4a19bba6cac 100644
--- a/products/ai_observability/backend/summarization/tests/test_providers.py
+++ b/products/ai_observability/backend/summarization/tests/test_providers.py
@@ -3,12 +3,38 @@ import json
import pytest
from unittest.mock import MagicMock, patch
+import httpx
+from openai import APIConnectionError, APIStatusError, BadRequestError, InternalServerError, RateLimitError, omit
from rest_framework import exceptions
+from products.ai_observability.backend.summarization.constants import SUMMARIZATION_FLEX_TIMEOUT, SUMMARIZATION_TIMEOUT
from products.ai_observability.backend.summarization.llm.openai import summarize_with_openai
from products.ai_observability.backend.summarization.llm.schema import SummarizationResponse
from products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationMode
+_REQUEST = httpx.Request("POST", "https://example.com/v1/chat/completions")
+
+
+def _rate_limit_error() -> RateLimitError:
+ return RateLimitError("rate limited", response=httpx.Response(429, request=_REQUEST), body=None)
+
+
+def _flex_408_error() -> APIStatusError:
+ # OpenAI answers a server-side flex timeout with 408, which the SDK raises as the bare
+ # APIStatusError because it has no named class for that status.
+ return APIStatusError("request timeout", response=httpx.Response(408, request=_REQUEST), body=None)
+
+
+def _gateway_ceiling_error() -> InternalServerError:
+ # The ai-gateway answers 504 when a buffered call outlives its ~290s response ceiling.
+ return InternalServerError("gateway timeout", response=httpx.Response(504, request=_REQUEST), body=None)
+
+
+def _connection_error() -> APIConnectionError:
+ # A proxy or LB resetting a long-parked flex request surfaces as the bare parent class,
+ # not APITimeoutError, so the fallback must catch APIConnectionError itself.
+ return APIConnectionError(request=_REQUEST)
+
@pytest.fixture
def valid_response_json():
@@ -31,6 +57,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
result = summarize_with_openai(
@@ -57,6 +84,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
with pytest.raises(exceptions.ValidationError, match="empty response"):
@@ -71,6 +99,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.side_effect = Exception("API Error")
with pytest.raises(exceptions.APIException, match="Failed to generate summary"):
@@ -89,6 +118,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
summarize_with_openai(
@@ -109,6 +139,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
summarize_with_openai(
@@ -130,6 +161,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
summarize_with_openai(
@@ -150,6 +182,7 @@ class TestSummarizeWithOpenAI:
with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
summarize_with_openai(
@@ -162,3 +195,110 @@ class TestSummarizeWithOpenAI:
call_kwargs = mock_client.chat.completions.create.call_args[1]
assert call_kwargs["response_format"]["type"] == "json_schema"
assert call_kwargs["response_format"]["json_schema"]["strict"] is True
+
+ @pytest.mark.parametrize(
+ "model,flex,expected_tier,expected_effort,expected_timeout",
+ [
+ (OpenAIModel.GPT_5_NANO, True, "flex", "minimal", SUMMARIZATION_FLEX_TIMEOUT),
+ (OpenAIModel.GPT_5_NANO, False, omit, "minimal", SUMMARIZATION_TIMEOUT),
+ # gpt-4.1 rejects service_tier, so a flex request must not forward it
+ (OpenAIModel.GPT_4_1_MINI, True, omit, omit, SUMMARIZATION_TIMEOUT),
+ ],
+ )
+ def test_flex_and_reasoning_effort_apply_only_to_gpt5(
+ self, valid_response_json, model, flex, expected_tier, expected_effort, expected_timeout
+ ):
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = valid_response_json
+
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
+ mock_client.chat.completions.create.return_value = mock_response
+
+ summarize_with_openai(
+ text_repr="L1: Test",
+ team_id=1,
+ mode=SummarizationMode.MINIMAL,
+ model=model,
+ flex=flex,
+ )
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("service_tier") == expected_tier
+ assert call_kwargs.get("reasoning_effort") == expected_effort
+ assert call_kwargs["timeout"] == expected_timeout
+ if expected_tier == "flex":
+ # The flex attempt must not inherit the SDK's default retries; the standard
+ # tier is its retry (see the budget math at the call site).
+ mock_client.with_options.assert_called_once_with(max_retries=0)
+
+ @pytest.mark.parametrize(
+ "flex_error", [_rate_limit_error(), _connection_error(), _gateway_ceiling_error(), _flex_408_error()]
+ )
+ def test_flex_failure_falls_back_to_standard_tier(self, valid_response_json, flex_error):
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = valid_response_json
+
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
+ mock_client.chat.completions.create.side_effect = [flex_error, mock_response]
+
+ result = summarize_with_openai(
+ text_repr="L1: Test",
+ team_id=1,
+ mode=SummarizationMode.MINIMAL,
+ model=OpenAIModel.GPT_5_NANO,
+ flex=True,
+ )
+
+ assert isinstance(result, SummarizationResponse)
+ assert mock_client.chat.completions.create.call_count == 2
+ retry_kwargs = mock_client.chat.completions.create.call_args_list[1][1]
+ assert retry_kwargs.get("service_tier") == omit
+ assert retry_kwargs["timeout"] == SUMMARIZATION_TIMEOUT
+
+ def test_flex_config_error_does_not_fall_back(self, valid_response_json):
+ # A 400 (bad request) on flex is a configuration bug the standard tier shares; falling
+ # back would mask it, so it must propagate instead.
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
+ mock_client.chat.completions.create.side_effect = BadRequestError(
+ "bad request", response=httpx.Response(400, request=_REQUEST), body=None
+ )
+
+ with pytest.raises(exceptions.APIException, match="Failed to generate summary"):
+ summarize_with_openai(
+ text_repr="L1: Test",
+ team_id=1,
+ mode=SummarizationMode.MINIMAL,
+ model=OpenAIModel.GPT_5_NANO,
+ flex=True,
+ )
+
+ assert mock_client.chat.completions.create.call_count == 1
+
+ def test_standard_tier_rate_limit_does_not_retry(self):
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_client.with_options.return_value = mock_client
+ mock_client.chat.completions.create.side_effect = _rate_limit_error()
+
+ with pytest.raises(exceptions.APIException, match="Failed to generate summary"):
+ summarize_with_openai(
+ text_repr="L1: Test",
+ team_id=1,
+ mode=SummarizationMode.MINIMAL,
+ model=OpenAIModel.GPT_5_NANO,
+ flex=False,
+ )
+
+ assert mock_client.chat.completions.create.call_count == 1
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 18b23b393059..436b01695d1d 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -251,19 +251,19 @@ Defined in `src/llm_gateway/products/config.py`:
OAuth access is permitted only for products with an explicit `allowed_application_ids` allowlist. All other products are API-key-only by default.
-| Product | Auth | Models | Notes |
-| -------------------- | --------------- | -------------------------- | ------------------------------- |
-| `llm_gateway` | API key only | All | Default when no product in path |
-| `ci` | API key only | All | CI / e2e test runs |
-| `posthog_code` | OAuth only | Restricted set | Desktop coding agent |
-| `background_agents` | OAuth only | Restricted set | Cloud background agents |
-| `onboarding` | OAuth only | claude-sonnet-5 | Unbilled setup wizard cloud run |
-| `wizard` | API key + OAuth | All | Max AI assistant |
-| `django` | API key only | All | Server-side Django calls |
-| `growth` | API key only | All | Growth team |
-| `llma_translation` | API key only | gpt-4.1-mini | AI observability translation |
-| `llma_summarization` | API key only | gpt-4.1-nano, gpt-4.1-mini | AI observability summarization |
-| `llma_eval_summary` | API key only | gpt-5-mini | AI observability eval summary |
+| Product | Auth | Models | Notes |
+| -------------------- | --------------- | -------------------------------------------------- | ------------------------------- |
+| `llm_gateway` | API key only | All | Default when no product in path |
+| `ci` | API key only | All | CI / e2e test runs |
+| `posthog_code` | OAuth only | Restricted set | Desktop coding agent |
+| `background_agents` | OAuth only | Restricted set | Cloud background agents |
+| `onboarding` | OAuth only | claude-sonnet-5 | Unbilled setup wizard cloud run |
+| `wizard` | API key + OAuth | All | Max AI assistant |
+| `django` | API key only | All | Server-side Django calls |
+| `growth` | API key only | All | Growth team |
+| `llma_translation` | API key only | gpt-4.1-mini | AI observability translation |
+| `llma_summarization` | API key only | gpt-4.1-nano, gpt-4.1-mini, gpt-5-nano, gpt-5-mini | AI observability summarization |
+| `llma_eval_summary` | API key only | gpt-5-mini | AI observability eval summary |
Aliases: `twig`, `array` resolve to `posthog_code`; `slack-twig` resolves to `slack-posthog-code`.
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index d16cda3b17fc..5263d2aae6d0 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -233,7 +233,9 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
),
"llma_summarization": ProductConfig(
allowed_application_ids=None,
- allowed_models=frozenset({"gpt-4.1-nano", "gpt-4.1-mini"}),
+ # Every value LLMA_SUMMARIZATION_MODEL realistically takes (rollback: gpt-4.1-nano,
+ # escalation: gpt-5-mini) must be servable here, or the fallback path 403s.
+ allowed_models=frozenset({"gpt-4.1-nano", "gpt-4.1-mini", "gpt-5-nano", "gpt-5-mini"}),
allow_api_keys=True,
),
"llma_eval_summary": ProductConfig(
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 803b372224c4..5f9ed29dcfdc 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -136,6 +136,13 @@ class TestCheckProductAccess:
True,
None,
),
+ # The batch trace summarization pipeline lands on this gateway when AI_GATEWAY_URL
+ # is unset. Its model missing from this list turns that fallback into a 403 on every
+ # call, which silently starves the clusters feature of summaries.
+ ("llma_summarization", "personal_api_key", None, "gpt-5-nano", True, None),
+ ("llma_summarization", "personal_api_key", None, "gpt-5-mini", True, None),
+ ("llma_summarization", "personal_api_key", None, "gpt-4.1-nano", True, None),
+ ("llma_summarization", "personal_api_key", None, "gpt-4o", False, "not allowed"),
# llma_translation allows API keys but only gpt-4.1-mini; OAuth rejected (no app IDs configured)
("llma_translation", "personal_api_key", None, "gpt-4.1-mini", True, None),
("llma_translation", "personal_api_key", None, "claude-3-opus", False, "not allowed"),