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): probe flex again after a capacity refusal (#98666)

Bernat Torres5335c1125688
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index 7ae81a265e91..5920e4257c55 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -7,7 +7,8 @@ its ``resolve_ai_gateway_config`` validator and ``ai_gateway_headers`` helper.
"""
import os
-from collections.abc import Mapping
+import time
+from collections.abc import AsyncIterator, Iterator, Mapping
from typing import Any, Literal
from django.conf import settings
@@ -19,9 +20,9 @@ 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_core.outputs import ChatGenerationChunk, ChatResult
from langchain_openai import ChatOpenAI
-from openai import APIError
+from openai import APIError, RateLimitError
from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from pydantic import PrivateAttr
from temporalio.exceptions import ApplicationError
@@ -38,6 +39,9 @@ logger = structlog.get_logger(__name__)
AI_FEATURES_CLOUD_ONLY_ERROR_TYPE = "AIFeaturesCloudOnly"
+FLEX_REPROBE_COOLDOWN = 60.0
+
+
class FlexFirstChatOpenAI(ChatOpenAI):
"""ChatOpenAI that retries a failed flex call once on the standard tier, per call.
@@ -45,30 +49,49 @@ class FlexFirstChatOpenAI(ChatOpenAI):
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.
+ the tier switch is the retry.
+
+ A fallback then holds the client on standard, because retrying a tier that just
+ refused wastes a call. How long it holds depends on what the tier cost to discover:
+ a capacity refusal pauses flex for ``FLEX_REPROBE_COOLDOWN`` and the run probes it
+ again, while a stall or a connection failure, which costs a full timeout to find,
+ latches the client for the rest of the run.
- Build one through ``build_flex_first_chat_client`` rather than directly, so every
- caller gets the same tier, timeout, and retry policy.
+ Build one through ``build_flex_first_chat_client`` rather than directly, and build
+ one per run: the latch and the cooldown are run policy, but ``_flex_requested`` is
+ per request, so concurrent calls on one client would overwrite each other's tier.
"""
_flex_latched: bool = PrivateAttr(default=False)
+ _flex_paused_until: float = PrivateAttr(default=0.0)
+ _flex_requested: bool = PrivateAttr(default=False)
+
+ def _flex_allowed_now(self) -> bool:
+ return self.service_tier == "flex" and not self._flex_latched and time.monotonic() >= self._flex_paused_until
def _get_request_payload(self, input_: LanguageModelInput, *, stop: list[str] | None = None, **kwargs: Any) -> dict:
- if self._flex_latched:
- kwargs = {**kwargs, "service_tier": "default"}
+ # Assign rather than guard: langchain builds the payload as {**defaults, **kwargs},
+ # so a caller-supplied service_tier would otherwise win and desync the flag.
+ if self.service_tier == "flex":
+ kwargs = {**kwargs, "service_tier": "flex" if self._flex_requested else "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):
+ # Only a call that went out as flex has a standard tier left to try.
+ if not self._flex_requested or not is_flex_recoverable(error):
raise error
+ if isinstance(error, RateLimitError):
+ self._flex_paused_until = time.monotonic() + FLEX_REPROBE_COOLDOWN
+ else:
+ self._flex_latched = True
logger.warning(
"flex_call_fell_back",
error_type=type(error).__name__,
status_code=getattr(error, "status_code", None),
model=self.model_name,
+ latched=self._flex_latched,
)
- self._flex_latched = True
+ self._flex_requested = False
def _generate(
self,
@@ -77,6 +100,9 @@ class FlexFirstChatOpenAI(ChatOpenAI):
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
+ # Take flex whenever it is allowed, and freeze that for the call. Re-reading
+ # allowance in the error handler would flip once a cooldown expired mid-call.
+ self._flex_requested = self._flex_allowed_now()
try:
return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
except APIError as error:
@@ -90,12 +116,24 @@ class FlexFirstChatOpenAI(ChatOpenAI):
run_manager: AsyncCallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
+ self._flex_requested = self._flex_allowed_now()
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)
+ # Streaming skips _generate, so it picks the tier itself. No fallback: tokens are
+ # already with the caller by the time an error arrives.
+ def _stream(self, *args: Any, **kwargs: Any) -> Iterator[ChatGenerationChunk]:
+ self._flex_requested = self._flex_allowed_now()
+ return super()._stream(*args, **kwargs)
+
+ async def _astream(self, *args: Any, **kwargs: Any) -> AsyncIterator[ChatGenerationChunk]:
+ self._flex_requested = self._flex_allowed_now()
+ async for chunk in super()._astream(*args, **kwargs):
+ yield chunk
+
def build_langchain_chat_client(
model: str,
diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
index 3ffa69354cc1..ad3bdbdf4f37 100644
--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
@@ -16,6 +16,7 @@ from posthog.llm.openai_flex import FLEX_CAPABLE_MODELS
from posthog.temporal.ai_observability.eval_reports.constants import EVAL_REPORT_AGENT_MODEL
from posthog.temporal.ai_observability.llm_endpoint import (
AI_FEATURES_CLOUD_ONLY_ERROR_TYPE,
+ FLEX_REPROBE_COOLDOWN,
FlexFirstChatOpenAI,
build_langchain_callbacks,
build_langchain_chat_client,
@@ -278,6 +279,47 @@ def _mock_create(*results: object) -> MagicMock:
return client
+def _mock_stream(is_async: bool = False) -> MagicMock:
+ """Mock client.create for a streamed completion: one content chunk, then a stop."""
+ chunks = [
+ {
+ "id": "1",
+ "object": "chat.completion.chunk",
+ "created": 0,
+ "model": "gpt-5.4",
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": "labeled"}, "finish_reason": None}],
+ },
+ {
+ "id": "1",
+ "object": "chat.completion.chunk",
+ "created": 0,
+ "model": "gpt-5.4",
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
+ },
+ ]
+
+ class _Stream:
+ def __enter__(self):
+ return iter(chunks)
+
+ def __exit__(self, *_):
+ return False
+
+ async def __aenter__(self):
+ async def gen():
+ for chunk in chunks:
+ yield chunk
+
+ return gen()
+
+ async def __aexit__(self, *_):
+ return False
+
+ client = MagicMock()
+ client.create = AsyncMock(return_value=_Stream()) if is_async else MagicMock(return_value=_Stream())
+ return client
+
+
class TestFlexFirstChatOpenAI:
@pytest.mark.parametrize(
"error",
@@ -311,7 +353,7 @@ class TestFlexFirstChatOpenAI:
assert llm.client.with_raw_response.create.call_count == 1
- def test_first_fallback_latches_the_client_to_standard(self):
+ def test_a_refusal_holds_the_client_on_standard_inside_the_cooldown(self):
llm = _flex_client()
llm.client = _mock_create(
RateLimitError("capacity refused", response=httpx.Response(429, request=_FLEX_REQUEST), body=None),
@@ -325,6 +367,56 @@ class TestFlexFirstChatOpenAI:
third = llm.client.with_raw_response.create.call_args_list[2]
assert third.kwargs["service_tier"] == "default"
+ @pytest.mark.parametrize(
+ "error,tier_after_cooldown",
+ [
+ (
+ RateLimitError("capacity refused", response=httpx.Response(429, request=_FLEX_REQUEST), body=None),
+ "flex",
+ ),
+ (APITimeoutError(request=_FLEX_REQUEST), "default"),
+ ],
+ )
+ def test_flex_returns_after_a_refusal_but_stays_off_after_a_stall(self, error, tier_after_cooldown):
+ llm = _flex_client()
+ llm.client = _mock_create(error, _COMPLETION, _COMPLETION)
+ clock = {"now": 0.0}
+
+ with patch("posthog.temporal.ai_observability.llm_endpoint.time.monotonic", lambda: clock["now"]):
+ llm.invoke("label the clusters")
+ clock["now"] = FLEX_REPROBE_COOLDOWN + 1
+ llm.invoke("label the next cluster")
+
+ third = llm.client.with_raw_response.create.call_args_list[2]
+ assert third.kwargs["service_tier"] == tier_after_cooldown
+
+ @pytest.mark.parametrize("latched,expected", [(False, "flex"), (True, "default")])
+ def test_streaming_asks_for_the_same_tier_as_a_buffered_call(self, latched, expected):
+ llm = _flex_client()
+ llm._flex_latched = latched
+ llm.client = _mock_stream()
+
+ list(llm.stream("label the clusters"))
+
+ assert llm.client.create.call_args.kwargs["service_tier"] == expected
+
+ async def test_async_streaming_asks_for_flex_too(self):
+ llm = _flex_client()
+ llm.async_client = _mock_stream(is_async=True)
+
+ async for _ in llm.astream("label the clusters"):
+ pass
+
+ assert llm.async_client.create.call_args.kwargs["service_tier"] == "flex"
+
+ def test_a_caller_cannot_override_the_tier_the_client_chose(self):
+ llm = _flex_client()
+ llm.client = _mock_create(_COMPLETION)
+
+ llm.invoke("label the clusters", service_tier="default")
+
+ assert llm.client.with_raw_response.create.call_args.kwargs["service_tier"] == "flex"
+
def test_standard_client_never_falls_back(self):
llm = _flex_client(service_tier=None)
llm.client = _mock_create(