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): run cluster labeling on the flex service tier (#92166)

Bernat Torresf65a9b667bf5
diff --git a/posthog/llm/openai_flex.py b/posthog/llm/openai_flex.py
new file mode 100644
index 000000000000..92728d72173d
--- /dev/null
+++ b/posthog/llm/openai_flex.py
@@ -0,0 +1,42 @@
+"""Which OpenAI models may request the flex service tier, and which failures escalate off it."""
+
+from openai import APIConnectionError, APIError, APIStatusError, InternalServerError, RateLimitError
+
+# OpenAI decides flex eligibility per model, and the pro tiers are excluded, so callers must
+# check membership here rather than infer it from a model family prefix. This mirrors the flex
+# table on https://developers.openai.com/api/docs/pricing?latest-pricing=flex (September 2026);
+# a new model joins only after someone checks that page.
+FLEX_CAPABLE_MODELS: frozenset[str] = frozenset(
+ {
+ "gpt-5.6-sol",
+ "gpt-5.6-terra",
+ "gpt-5.6-luna",
+ "gpt-5.5",
+ "gpt-5.4",
+ "gpt-5.4-mini",
+ "gpt-5.4-nano",
+ "gpt-5.2",
+ "gpt-5.1",
+ "gpt-5",
+ "gpt-5-mini",
+ "gpt-5-nano",
+ "o3",
+ "o4-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/409, which the SDK's own retry loop also
+ retries and raises as the bare APIStatusError (OpenAI's flex docs use 408 for a
+ server-side flex timeout). 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 in (408, 409)
diff --git a/posthog/temporal/ai_observability/clustering_agent/__init__.py b/posthog/temporal/ai_observability/clustering_agent/__init__.py
index f0e7aaea514e..e15344188b2c 100644
--- a/posthog/temporal/ai_observability/clustering_agent/__init__.py
+++ b/posthog/temporal/ai_observability/clustering_agent/__init__.py
@@ -12,10 +12,18 @@ from collections.abc import Mapping
from langchain_openai import ChatOpenAI
+from posthog.llm.openai_flex import FLEX_CAPABLE_MODELS
from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
from posthog.temporal.ai_observability.trace_clustering.constants import NOISE_CLUSTER_ID
from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel
+# Per-call timeouts, capped so no single call can outlive the 600s labeling activity: flex
+# 120s x 1 attempt (the standard-tier fallback call is the retry), standard 240s x 2 attempts.
+# The ai-gateway cuts non-streaming calls at ~290s anyway, so longer client timeouts are
+# unreachable.
+LABELING_FLEX_CALL_TIMEOUT = 120.0
+LABELING_STANDARD_CALL_TIMEOUT = 240.0
+
def get_labeling_llm(
model: str,
@@ -25,6 +33,7 @@ def get_labeling_llm(
session_id: str,
properties: Mapping[str, str],
distinct_id: str,
+ flex: bool = True,
) -> ChatOpenAI:
"""Return a ChatOpenAI client for cluster labeling.
@@ -32,15 +41,22 @@ def get_labeling_llm(
ai-gateway when configured; see
``posthog.temporal.ai_observability.llm_endpoint``. Enforces the same
guardrail as before: AI features only run in Cloud or local DEBUG builds.
+
+ Labeling runs as a daily batch, so allowlisted models request the flex
+ service tier for half-price tokens; ``FlexFirstChatOpenAI`` retries a failed
+ flex call on the standard tier.
"""
+ use_flex = flex and model in FLEX_CAPABLE_MODELS
return build_langchain_chat_client(
model,
- timeout,
+ LABELING_FLEX_CALL_TIMEOUT if use_flex else min(timeout, LABELING_STANDARD_CALL_TIMEOUT),
ai_product="aio_clustering",
trace_id=trace_id,
session_id=session_id,
properties=properties,
distinct_id=distinct_id,
+ service_tier="flex" if use_flex else None,
+ max_retries=0 if use_flex else 1,
)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py b/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py
index 23b349fd1cae..a6a98fc29f3c 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/coordinator.py
@@ -27,6 +27,7 @@ from posthog.temporal.ai_observability.evaluation_clustering.workflow import (
AIObservabilityEvaluationClusteringWorkflow,
AIObservabilityEvaluationSamplerWorkflow,
)
+from posthog.temporal.ai_observability.trace_clustering.constants import WORKFLOW_EXECUTION_TIMEOUT
from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
@@ -268,7 +269,7 @@ class AIObservabilityEvaluationClusteringCoordinatorWorkflow(PostHogWorkflow):
id=(
f"{CLUSTERING_CHILD_WORKFLOW_ID_PREFIX}-{team_id}-{job.job_id}-{workflow.now().isoformat()}"
),
- execution_timeout=timedelta(minutes=30),
+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
retry_policy=SAMPLER_CHILD_WORKFLOW_RETRY_POLICY,
parent_close_policy=workflow.ParentClosePolicy.TERMINATE,
)
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index 415faad71a8f..7af14d07baa9 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -8,18 +8,29 @@ its ``resolve_ai_gateway_config`` validator and ``ai_gateway_headers`` helper.
import os
from collections.abc import Mapping
+from typing import Any, Literal
from django.conf import settings
import httpx
+import structlog
import posthoganalytics
from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.callbacks.manager import AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import ChatResult
from langchain_openai import ChatOpenAI
+from openai import APIError
from posthoganalytics.ai.langchain.callbacks import CallbackHandler
+from pydantic import PrivateAttr
from temporalio.exceptions import ApplicationError
from posthog.cloud_utils import is_cloud
from posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_config
+from posthog.llm.openai_flex import is_flex_recoverable
+
+logger = structlog.get_logger(__name__)
# On a non-cloud, non-DEBUG deployment there is no AI gateway, so this guard fails identically
# every run. The interceptor in posthog/temporal/common/posthog_client.py keeps this error type
@@ -27,6 +38,62 @@ from posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_co
AI_FEATURES_CLOUD_ONLY_ERROR_TYPE = "AIFeaturesCloudOnly"
+class FlexFirstChatOpenAI(ChatOpenAI):
+ """ChatOpenAI that retries a failed flex call once on the standard tier, per call.
+
+ The openai SDK's retry loop re-sends the byte-identical request, so it can only
+ re-roll a flex capacity refusal. This override retries just the failing chat
+ completion with service_tier="default", so an agent loop keeps its completed
+ turns instead of rerunning from scratch. Build flex clients with max_retries=0:
+ the tier switch is the retry. The first fallback latches the client to standard,
+ so a flex brownout costs one timeout per agent run, not one per call.
+ """
+
+ _flex_latched: bool = PrivateAttr(default=False)
+
+ def _get_request_payload(self, input_: LanguageModelInput, *, stop: list[str] | None = None, **kwargs: Any) -> dict:
+ if self._flex_latched:
+ kwargs = {**kwargs, "service_tier": "default"}
+ return super()._get_request_payload(input_, stop=stop, **kwargs)
+
+ def _latch_or_raise(self, error: APIError) -> None:
+ if self._flex_latched or self.service_tier != "flex" or not is_flex_recoverable(error):
+ raise error
+ logger.warning(
+ "labeling_flex_call_fell_back",
+ error_type=type(error).__name__,
+ status_code=getattr(error, "status_code", None),
+ model=self.model_name,
+ )
+ self._flex_latched = True
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ try:
+ return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
+ except APIError as error:
+ self._latch_or_raise(error)
+ return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ try:
+ return await super()._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs)
+ except APIError as error:
+ self._latch_or_raise(error)
+ return await super()._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs)
+
+
def build_langchain_chat_client(
model: str,
timeout: float,
@@ -35,6 +102,8 @@ def build_langchain_chat_client(
session_id: str | None = None,
properties: Mapping[str, str] | None = None,
distinct_id: str | None = None,
+ service_tier: Literal["flex"] | None = None,
+ max_retries: int = 2,
) -> ChatOpenAI:
"""Return a ChatOpenAI client for the labeling/report agents. Cloud/DEBUG only.
@@ -53,12 +122,12 @@ def build_langchain_chat_client(
gateway = resolve_ai_gateway_config()
if gateway:
- return ChatOpenAI(
+ return FlexFirstChatOpenAI(
model=model,
api_key=gateway.api_key,
base_url=gateway.url,
timeout=timeout,
- max_retries=2,
+ max_retries=max_retries,
default_headers=ai_gateway_headers(
ai_product=ai_product,
trace_id=trace_id,
@@ -69,12 +138,15 @@ def build_langchain_chat_client(
# trust_env=False keeps the in-cluster gateway call off the egress proxy.
http_client=httpx.Client(trust_env=False),
http_async_client=httpx.AsyncClient(trust_env=False),
+ service_tier=service_tier,
)
direct_key = os.environ.get("OPENAI_API_KEY")
if not direct_key:
raise Exception("OPENAI_API_KEY is not configured")
- return ChatOpenAI(model=model, api_key=direct_key, timeout=timeout, max_retries=2)
+ return FlexFirstChatOpenAI(
+ model=model, api_key=direct_key, timeout=timeout, max_retries=max_retries, service_tier=service_tier
+ )
def build_langchain_callbacks(
diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
index 5ae7ba411895..59cd02f5ec1e 100644
--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
@@ -3,14 +3,18 @@
import json
import pytest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.test import override_settings
+import httpx
+import openai
+from openai import APIStatusError, APITimeoutError, InternalServerError, RateLimitError
from temporalio.exceptions import ApplicationError
from posthog.temporal.ai_observability.llm_endpoint import (
AI_FEATURES_CLOUD_ONLY_ERROR_TYPE,
+ FlexFirstChatOpenAI,
build_langchain_callbacks,
build_langchain_chat_client,
)
@@ -88,7 +92,7 @@ class TestBuildOpenAIChatClient:
@override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)
def test_gateway_mode_tags_ai_product_via_posthog_properties_header(self):
- with patch("posthog.temporal.ai_observability.llm_endpoint.ChatOpenAI") as mock_chat:
+ with patch("posthog.temporal.ai_observability.llm_endpoint.FlexFirstChatOpenAI") as mock_chat:
build_langchain_chat_client(
"gpt-5.4",
600.0,
@@ -117,7 +121,7 @@ class TestBuildOpenAIChatClient:
@override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)
def test_gateway_mode_without_ai_product_omits_header(self):
- with patch("posthog.temporal.ai_observability.llm_endpoint.ChatOpenAI") as mock_chat:
+ with patch("posthog.temporal.ai_observability.llm_endpoint.FlexFirstChatOpenAI") as mock_chat:
build_langchain_chat_client("gpt-5.4", 600.0)
assert mock_chat.call_args.kwargs["default_headers"] is None
@@ -163,3 +167,182 @@ class TestBuildOpenAIChatClient:
assert callbacks == []
mock_callback.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "service_tier,expected",
+ [
+ ("flex", "flex"),
+ (None, None),
+ ],
+ )
+ def test_service_tier_reaches_the_client_in_both_routing_modes(self, service_tier, expected):
+ # Dropping the tier silently doubles the labeling bill, so pin the passthrough.
+ for gateway_url, gateway_key in [(GATEWAY_URL, GATEWAY_KEY), (None, None)]:
+ with (
+ override_settings(DEBUG=True, AI_GATEWAY_URL=gateway_url, AI_GATEWAY_API_KEY=gateway_key),
+ patch.dict("os.environ", {"OPENAI_API_KEY": "sk-direct"}, clear=False),
+ ):
+ client = build_langchain_chat_client("gpt-5.4", 600.0, service_tier=service_tier)
+ assert client.service_tier == expected
+
+ @pytest.mark.parametrize(
+ "model,expected_tier",
+ [
+ ("gpt-5.4", "flex"),
+ # OpenAI excludes pro tiers from flex, so the family prefix must not grant it.
+ ("gpt-5.4-pro", None),
+ # gpt-4.1 models reject the service_tier field, so a fallback to them must not send it.
+ ("gpt-4.1-mini", None),
+ ],
+ )
+ def test_labeling_llm_requests_flex_only_for_allowlisted_models(self, model, expected_tier):
+ from posthog.temporal.ai_observability.clustering_agent import get_labeling_llm
+
+ with (
+ override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY),
+ ):
+ client = get_labeling_llm(
+ model,
+ 600.0,
+ trace_id="t",
+ session_id="s",
+ properties={},
+ distinct_id="d",
+ )
+ assert client.service_tier == expected_tier
+
+ def test_labeling_clients_bound_every_call_inside_the_activity_budget(self):
+ from posthog.temporal.ai_observability.clustering_agent import (
+ LABELING_FLEX_CALL_TIMEOUT,
+ LABELING_STANDARD_CALL_TIMEOUT,
+ get_labeling_llm,
+ )
+
+ with override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY):
+ flex_client = get_labeling_llm(
+ "gpt-5.4", 600.0, trace_id="t", session_id="s", properties={}, distinct_id="d"
+ )
+ standard_client = get_labeling_llm(
+ "gpt-5.4", 600.0, trace_id="t", session_id="s", properties={}, distinct_id="d", flex=False
+ )
+
+ # Flex: 120s x 1 attempt (the standard-tier fallback call is the retry); standard: 240s x 2 = 480s.
+ # Both fit the 600s activity budget, where the old 600s x 3 attempts per call could not.
+ assert flex_client.request_timeout == LABELING_FLEX_CALL_TIMEOUT
+ assert flex_client.max_retries == 0
+ assert standard_client.service_tier is None
+ assert standard_client.request_timeout == LABELING_STANDARD_CALL_TIMEOUT
+ assert standard_client.max_retries == 1
+
+
+_FLEX_REQUEST = httpx.Request("POST", "https://api.openai.com/v1/chat/completions")
+
+_COMPLETION = {
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-5.4",
+ "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "labeled"}}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+}
+
+
+def _flex_client(service_tier: str | None = "flex") -> FlexFirstChatOpenAI:
+ return FlexFirstChatOpenAI(
+ model="gpt-5.4",
+ api_key="sk-test",
+ max_retries=0,
+ service_tier=service_tier,
+ )
+
+
+def _mock_create(*results: object) -> MagicMock:
+ """Mock client.with_raw_response.create: raise exceptions as-is, wrap dicts as raw responses."""
+
+ def to_side_effect(result: object) -> object:
+ if isinstance(result, Exception):
+ return result
+ raw = MagicMock()
+ raw.parse.return_value = result
+ raw.headers = {}
+ return raw
+
+ create = MagicMock(side_effect=[to_side_effect(result) for result in results])
+ client = MagicMock()
+ client.with_raw_response.create = create
+ return client
+
+
+class TestFlexFirstChatOpenAI:
+ @pytest.mark.parametrize(
+ "error",
+ [
+ RateLimitError("capacity refused", response=httpx.Response(429, request=_FLEX_REQUEST), body=None),
+ APIStatusError("flex timeout", response=httpx.Response(408, request=_FLEX_REQUEST), body=None),
+ InternalServerError("gateway 504", response=httpx.Response(504, request=_FLEX_REQUEST), body=None),
+ APITimeoutError(request=_FLEX_REQUEST),
+ APIStatusError("conflict", response=httpx.Response(409, request=_FLEX_REQUEST), body=None),
+ ],
+ )
+ def test_recoverable_flex_failure_retries_that_call_on_standard(self, error):
+ llm = _flex_client()
+ llm.client = _mock_create(error, _COMPLETION)
+
+ result = llm.invoke("label the clusters")
+
+ assert result.content == "labeled"
+ first, second = llm.client.with_raw_response.create.call_args_list
+ assert first.kwargs["service_tier"] == "flex"
+ assert second.kwargs["service_tier"] == "default"
+
+ def test_non_recoverable_error_propagates_without_fallback(self):
+ llm = _flex_client()
+ llm.client = _mock_create(
+ openai.BadRequestError("bad request", response=httpx.Response(400, request=_FLEX_REQUEST), body=None)
+ )
+
+ with pytest.raises(openai.BadRequestError):
+ llm.invoke("label the clusters")
+
+ assert llm.client.with_raw_response.create.call_count == 1
+
+ def test_first_fallback_latches_the_client_to_standard(self):
+ llm = _flex_client()
+ llm.client = _mock_create(
+ RateLimitError("capacity refused", response=httpx.Response(429, request=_FLEX_REQUEST), body=None),
+ _COMPLETION,
+ _COMPLETION,
+ )
+
+ llm.invoke("label the clusters")
+ llm.invoke("label the next cluster")
+
+ third = llm.client.with_raw_response.create.call_args_list[2]
+ assert third.kwargs["service_tier"] == "default"
+
+ def test_standard_client_never_falls_back(self):
+ llm = _flex_client(service_tier=None)
+ llm.client = _mock_create(
+ RateLimitError("rate limited", response=httpx.Response(429, request=_FLEX_REQUEST), body=None)
+ )
+
+ with pytest.raises(RateLimitError):
+ llm.invoke("label the clusters")
+
+ assert llm.client.with_raw_response.create.call_count == 1
+
+ @pytest.mark.asyncio
+ async def test_async_path_falls_back_too(self):
+ llm = _flex_client()
+ flex_raw = RateLimitError("capacity refused", response=httpx.Response(429, request=_FLEX_REQUEST), body=None)
+ standard_raw = MagicMock()
+ standard_raw.parse.return_value = _COMPLETION
+ standard_raw.headers = {}
+ create = AsyncMock(side_effect=[flex_raw, standard_raw])
+ llm.async_client = MagicMock()
+ llm.async_client.with_raw_response.create = create
+
+ result = await llm.ainvoke("label the clusters")
+
+ assert result.content == "labeled"
+ assert create.call_args_list[1].kwargs["service_tier"] == "default"
diff --git a/posthog/temporal/ai_observability/trace_clustering/constants.py b/posthog/temporal/ai_observability/trace_clustering/constants.py
index 135b6898d3b5..0e4ff0eead1a 100644
--- a/posthog/temporal/ai_observability/trace_clustering/constants.py
+++ b/posthog/temporal/ai_observability/trace_clustering/constants.py
@@ -54,7 +54,9 @@ EMIT_HEARTBEAT_TIMEOUT = timedelta(seconds=30) # 30 seconds - ClickHouse writes
# backoff intervals, and queue time. Prevents runaway retries from blocking
# the workflow indefinitely.
COMPUTE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=720) # Two attempts, 60s backoff, and queue time
-LLM_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=900) # 15 min (2 attempts * 600s + backoff, capped)
+LLM_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(
+ seconds=1260
+) # 21 min: 2 attempts * 600s + backoff, so a timed-out first attempt still leaves the retry a full run
AGGREGATES_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=330) # 5.5 min (1 attempt only, best-effort)
EMIT_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=150) # 2.5 min (2 attempts * 60s + backoff)
diff --git a/products/ai_observability/backend/summarization/llm/openai.py b/products/ai_observability/backend/summarization/llm/openai.py
index 888ccd628b90..306466df10db 100644
--- a/products/ai_observability/backend/summarization/llm/openai.py
+++ b/products/ai_observability/backend/summarization/llm/openai.py
@@ -4,11 +4,12 @@ when configured, else the Python LLM gateway."""
from typing import Any, Literal
import structlog
-from openai import APIConnectionError, APIError, APIStatusError, InternalServerError, Omit, OpenAI, RateLimitError, omit
+from openai import APIError, Omit, OpenAI, 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 posthog.llm.openai_flex import FLEX_CAPABLE_MODELS, is_flex_recoverable
from ..constants import SUMMARIZATION_FLEX_TIMEOUT, SUMMARIZATION_TIMEOUT
from ..models import OpenAIModel, SummarizationMode
@@ -22,27 +23,6 @@ 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 = {
@@ -108,9 +88,9 @@ def summarize_with_openai(
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
+ # 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):
+ if not is_flex_recoverable(flex_error):
raise
logger.info(
"summarization_flex_fell_back",