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(posthog-ai): route the root agent loop through the ai-gateway (#101277)

Brandon1f7508258b74
diff --git a/ee/hogai/core/agent_modes/executables.py b/ee/hogai/core/agent_modes/executables.py
index f7bdaef4dfe3..a24c7eb53e0a 100644
--- a/ee/hogai/core/agent_modes/executables.py
+++ b/ee/hogai/core/agent_modes/executables.py
@@ -33,6 +33,7 @@ from posthog.schema import (
)
from posthog.event_usage import groups
+from posthog.llm.gateway_client import resolve_ai_gateway_config
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
@@ -272,30 +273,31 @@ class AgentExecutable(BaseAgentLoopRootExecutable):
}
def _get_model(self, state: AssistantState, tools: list["MaxTool"]):
- gateway_kwargs = self._get_gateway_kwargs()
- is_routing_through_llm_gateway = bool(gateway_kwargs)
-
- base_model = MaxChatAnthropic(
- model="claude-sonnet-4-6",
- streaming=True,
- stream_usage=True,
- user=self._user,
- team=self._team,
- betas=[
+ model_kwargs: dict[str, Any] = {
+ "model": "claude-sonnet-4-6",
+ "streaming": True,
+ "stream_usage": True,
+ "user": self._user,
+ "team": self._team,
+ "betas": [
"interleaved-thinking-2025-05-14",
"fine-grained-tool-streaming-2025-05-14",
],
- max_tokens=16384,
- thinking=self.THINKING_CONFIG,
+ "max_tokens": 16384,
+ "thinking": self.THINKING_CONFIG,
# langchain-anthropic 0.3.x doesn't have a first-class effort field;
# forward it via model_kwargs so the Anthropic API receives output_config.
- model_kwargs={"output_config": {"effort": "medium"}},
- conversation_start_dt=state.start_dt,
- billable=True,
- bypass_proxy=is_routing_through_llm_gateway,
- posthog_properties=self._get_agent_mode_posthog_properties(state),
- **gateway_kwargs,
- )
+ "model_kwargs": {"output_config": {"effort": "medium"}},
+ "conversation_start_dt": state.start_dt,
+ "billable": True,
+ "posthog_properties": self._get_agent_mode_posthog_properties(state),
+ }
+
+ if ai_gateway := resolve_ai_gateway_config():
+ base_model = MaxChatAnthropic.via_ai_gateway(ai_gateway, **model_kwargs)
+ else:
+ gateway_kwargs = self._get_gateway_kwargs()
+ base_model = MaxChatAnthropic(**model_kwargs, bypass_proxy=bool(gateway_kwargs), **gateway_kwargs)
# The agent can operate in loops. Since insight building is an expensive operation, we want to limit a recursion depth.
# This will remove the functions, so the agent doesn't have any other option but to exit.
diff --git a/ee/hogai/core/agent_modes/test/test_executables.py b/ee/hogai/core/agent_modes/test/test_executables.py
index cfe848f4729b..2023a55490b8 100644
--- a/ee/hogai/core/agent_modes/test/test_executables.py
+++ b/ee/hogai/core/agent_modes/test/test_executables.py
@@ -1,11 +1,13 @@
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
from langchain_core.messages import (
AIMessage as LangchainAIMessage,
HumanMessage as LangchainHumanMessage,
)
-from langchain_core.runnables import RunnableConfig
+from langchain_core.runnables import RunnableBinding, RunnableConfig
from parameterized import parameterized
from posthog.schema import (
@@ -21,6 +23,7 @@ from posthog.models import Team, User
from ee.hogai.chat_agent.mode_manager import ChatAgentModeManager
from ee.hogai.context import AssistantContextManager
+from ee.hogai.llm import MaxChatAnthropic
from ee.hogai.tool_errors import MaxToolError, MaxToolFatalError, MaxToolRetryableError, MaxToolTransientError
from ee.hogai.tools.read_taxonomy.core import ReadEvents
from ee.hogai.utils.tests import FakeChatAnthropic, FakeChatOpenAI
@@ -1157,3 +1160,46 @@ class TestRootNodeTools(BaseTest):
from pydantic import ValidationError as PydanticValidationError
self.assertIsInstance(captured_error, PydanticValidationError)
+
+
[email protected]("os.environ", {"ANTHROPIC_API_KEY": "direct-api-key"})
+class TestAgentNodeModelRouting(BaseTest):
+ def _root_model(self) -> MaxChatAnthropic:
+ node = _create_agent_node(self.team, self.user)
+ model = node._get_model(AssistantState(messages=[HumanMessage(content="Hello")]), [])
+ assert isinstance(model, RunnableBinding)
+ assert isinstance(model.bound, MaxChatAnthropic)
+ return model.bound
+
+ @override_settings(
+ AI_GATEWAY_URL="https://ai-gateway.test/v1",
+ AI_GATEWAY_API_KEY="phs_gateway",
+ LLM_GATEWAY_URL="http://llm-gateway.test",
+ LLM_GATEWAY_API_KEY="legacy-key",
+ )
+ @patch("ee.hogai.core.agent_modes.executables.get_llm_gateway_variant", return_value="gateway-bedrock")
+ def test_root_model_routes_through_the_ai_gateway_when_configured(self, mock_variant):
+ root_model = self._root_model()
+
+ self.assertEqual(root_model.anthropic_api_url, "https://ai-gateway.test")
+ self.assertIsNone(root_model.default_headers)
+ assert isinstance(root_model.ai_gateway_fallback, MaxChatAnthropic)
+ self.assertEqual(root_model.ai_gateway_fallback.model, "claude-sonnet-4-6")
+ self.assertTrue(root_model.billable)
+ mock_variant.assert_not_called()
+
+ @override_settings(
+ AI_GATEWAY_URL="",
+ AI_GATEWAY_API_KEY="",
+ LLM_GATEWAY_URL="http://llm-gateway.test",
+ LLM_GATEWAY_API_KEY="legacy-key",
+ )
+ @patch("ee.hogai.core.agent_modes.executables.get_llm_gateway_variant", return_value="gateway-bedrock")
+ def test_root_model_keeps_the_legacy_gateway_arm_without_ai_gateway_config(self, _mock_variant):
+ root_model = self._root_model()
+
+ self.assertIsNone(root_model.ai_gateway_fallback)
+ self.assertEqual(root_model.anthropic_api_url, "http://llm-gateway.test/django")
+ assert root_model.default_headers is not None
+ self.assertEqual(root_model.default_headers["X-PostHog-Provider"], "bedrock")
+ self.assertTrue(root_model.bypass_proxy)
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.py
index cdec2658aeab..312226881ee0 100644
--- a/ee/hogai/core/runner.py
+++ b/ee/hogai/core/runner.py
@@ -12,12 +12,13 @@ import structlog
import posthoganalytics
from asgiref.sync import async_to_sync
from langchain_core.callbacks.base import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
from langchain_core.runnables.config import RunnableConfig
from langgraph.errors import GraphInterrupt, GraphRecursionError
from langgraph.graph.state import CompiledStateGraph
from langgraph.types import Command, StreamMode
from opentelemetry import trace
-from posthoganalytics.ai.langchain.callbacks import CallbackHandler
+from posthoganalytics.ai.langchain.callbacks import CallbackHandler, GenerationMetadata
from posthog.schema import (
AssistantEventType,
@@ -45,6 +46,7 @@ from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.core.ai_event_truncation import ai_event_truncator
from ee.hogai.core.base import BaseAssistantGraph
from ee.hogai.core.stream_processor import AssistantStreamProcessorProtocol
+from ee.hogai.llm import POSTHOG_AI_PRODUCT, is_ai_gateway_served
from ee.hogai.tool import ApprovalRequest, ClientToolCallRequest
from ee.hogai.utils.exceptions import (
AGENT_RUN_UNHANDLED_ERROR_COUNTER,
@@ -76,7 +78,27 @@ logger = structlog.get_logger(__name__)
_tracer = trace.get_tracer(__name__)
-class SubagentCallbackHandler(CallbackHandler):
+class MaxCallbackHandler(CallbackHandler):
+ """
+ Skips $ai_generation for gateway-served calls, which the gateway captures. $ai_trace and $ai_span still emit
+ because the AI credits query decides free turns from them.
+ """
+
+ def _capture_generation(
+ self,
+ trace_id: Any,
+ run_id: UUID,
+ run: GenerationMetadata,
+ output: LLMResult | BaseException,
+ parent_run_id: Optional[UUID] = None,
+ include_parent_id: bool = True,
+ ):
+ if is_ai_gateway_served(output):
+ return
+ super()._capture_generation(trace_id, run_id, run, output, parent_run_id, include_parent_id)
+
+
+class SubagentCallbackHandler(MaxCallbackHandler):
"""
Callback handler for subagents that makes all events appear as children of a parent span.
@@ -120,8 +142,11 @@ class BaseAgentRunner(ABC):
_parent_span_id: Optional[str | UUID]
_slack_thread_context: Optional["SlackThreadContext"]
_is_agent_billable: bool
+ _is_impersonated: bool
_resume_payload: Optional[dict[str, Any]]
_event_source: EventSource
+ _ai_product: Optional[str]
+ _privacy_mode: Optional[bool]
def __init__(
self,
@@ -167,11 +192,18 @@ class BaseAgentRunner(ABC):
self._graph = graph
self._callback_handlers = []
+ self._privacy_mode = None
if callback_handler:
self._callback_handlers.append(callback_handler)
+ # A caller's handler would capture gateway-served generations again, so these runs stay direct.
+ self._ai_product = None
else:
+ self._ai_product = "mcp" if self._conversation.type == Conversation.Type.TOOL_CALL else POSTHOG_AI_PRODUCT
def init_handler(client: posthoganalytics.Client):
+ # Evaluated lazily: the flag call creates a posthoganalytics default client when none exists.
+ if self._privacy_mode is None:
+ self._privacy_mode = is_privacy_mode_enabled(team)
callback_properties = {
"conversation_id": str(self._conversation.id),
"$ai_session_id": str(self._conversation.id),
@@ -180,7 +212,7 @@ class BaseAgentRunner(ABC):
"is_subagent": not self._use_checkpointer,
"$groups": event_usage.groups(team=team),
"ai_support_impersonated": is_impersonated,
- "ai_product": "mcp" if self._conversation.type == Conversation.Type.TOOL_CALL else "posthog_ai",
+ "ai_product": self._ai_product,
"conversation_type": self._conversation.type,
}
# Use SubagentCallbackHandler when parent_span_id is provided to nest all events under the parent
@@ -190,15 +222,15 @@ class BaseAgentRunner(ABC):
distinct_id=user.distinct_id if user else None,
properties=callback_properties,
trace_id=trace_id,
- privacy_mode=is_privacy_mode_enabled(team),
+ privacy_mode=self._privacy_mode,
parent_span_id=parent_span_id,
)
- return CallbackHandler(
+ return MaxCallbackHandler(
client,
distinct_id=user.distinct_id if user else None,
properties=callback_properties,
trace_id=trace_id,
- privacy_mode=is_privacy_mode_enabled(team),
+ privacy_mode=self._privacy_mode,
)
# flush_at=1 flushes each event immediately so traces deliver before short runs end;
@@ -225,6 +257,7 @@ class BaseAgentRunner(ABC):
self._billing_context = billing_context
self._initial_state = initial_state
self._is_agent_billable = is_agent_billable
+ self._is_impersonated = is_impersonated
# Initialize the stream processor with node configuration
self._stream_processor = stream_processor
self._slack_thread_context = slack_thread_context
@@ -527,6 +560,9 @@ class BaseAgentRunner(ABC):
"is_subagent": not self._use_checkpointer,
"slack_thread_context": self._slack_thread_context,
"is_agent_billable": self._is_agent_billable,
+ "is_impersonated": self._is_impersonated,
+ "ai_product": self._ai_product,
+ "privacy_mode": self._privacy_mode,
"event_source": self._event_source,
# Metadata to be sent to PostHog SDK (error tracking, etc).
"sdk_metadata": {
diff --git a/ee/hogai/core/test/test_base_callback_handlers.py b/ee/hogai/core/test/test_base_callback_handlers.py
index bbfe8f9f30cb..69df1e648122 100644
--- a/ee/hogai/core/test/test_base_callback_handlers.py
+++ b/ee/hogai/core/test/test_base_callback_handlers.py
@@ -3,14 +3,19 @@ from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
+from django.test import SimpleTestCase
+
import posthoganalytics
+from langchain_core.messages import AIMessage, HumanMessage
+from langchain_core.outputs import ChatGeneration, LLMResult
from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.chat_agent.runner import ChatAgentRunner
from ee.hogai.core.ai_event_truncation import ai_event_truncator
-from ee.hogai.core.runner import SubagentCallbackHandler
+from ee.hogai.core.runner import MaxCallbackHandler, SubagentCallbackHandler
+from ee.hogai.llm import AI_GATEWAY_SERVED_KEY
class TestBaseAgentRunnerCallbackHandlers(BaseTest):
@@ -138,7 +143,7 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):
trace_id = uuid4()
session_id = "test-session"
- with patch("ee.hogai.core.runner.CallbackHandler") as mock_callback_handler_class:
+ with patch("ee.hogai.core.runner.MaxCallbackHandler") as mock_callback_handler_class:
mock_handler_instance = Mock()
mock_callback_handler_class.return_value = mock_handler_instance
@@ -229,6 +234,7 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):
self.assertEqual(len(runner._callback_handlers), 1)
self.assertIsInstance(runner._callback_handlers[0], CallbackHandler)
self.assertNotIsInstance(runner._callback_handlers[0], SubagentCallbackHandler)
+ self.assertIsInstance(runner._callback_handlers[0], MaxCallbackHandler)
class TestSubagentCallbackHandler(BaseTest):
@@ -311,3 +317,106 @@ class TestSubagentCallbackHandler(BaseTest):
root_props = capture_calls[1][1]["properties"]
self.assertEqual(root_event, "$ai_span")
self.assertEqual(root_props["$ai_parent_id"], self.parent_span_id)
+
+
+class TestMaxCallbackHandler(SimpleTestCase):
+ def _captured_events(
+ self, client: Mock, handler: MaxCallbackHandler, output: LLMResult | BaseException
+ ) -> list[str]:
+ root_run_id, llm_run_id = uuid4(), uuid4()
+ handler.on_chain_start({"name": "Root"}, {"input": "hello"}, run_id=root_run_id, parent_run_id=None)
+ handler.on_chat_model_start(
+ {"name": "MaxChatAnthropic"},
+ [[HumanMessage(content="hello")]],
+ run_id=llm_run_id,
+ parent_run_id=root_run_id,
+ )
+ if isinstance(output, BaseException):
+ handler.on_llm_error(output, run_id=llm_run_id, parent_run_id=root_run_id)
+ else:
+ handler.on_llm_end(output, run_id=llm_run_id, parent_run_id=root_run_id)
+ handler.on_chain_end({"output": "done"}, run_id=root_run_id, parent_run_id=None)
+ return [call.kwargs["event"] for call in client.capture.call_args_list]
+
+ def _result(self, served: bool) -> LLMResult:
+ generation_info = {AI_GATEWAY_SERVED_KEY: True} if served else None
+ return LLMResult(
+ generations=[[ChatGeneration(message=AIMessage(content="hi"), generation_info=generation_info)]]
+ )
+
+ def test_skips_generations_the_gateway_served_and_keeps_the_trace(self):
+ client = Mock()
+ handler = MaxCallbackHandler(client, distinct_id="user", trace_id="trace-1")
+
+ self.assertEqual(self._captured_events(client, handler, self._result(served=True)), ["$ai_trace"])
+
+ def test_captures_generations_served_directly(self):
+ client = Mock()
+ handler = MaxCallbackHandler(client, distinct_id="user", trace_id="trace-1")
+
+ self.assertEqual(
+ self._captured_events(client, handler, self._result(served=False)), ["$ai_generation", "$ai_trace"]
+ )
+
+ def test_captures_failed_generations(self):
+ client = Mock()
+ handler = MaxCallbackHandler(client, distinct_id="user", trace_id="trace-1")
+
+ self.assertIn("$ai_generation", self._captured_events(client, handler, ValueError("failed")))
+
+ def test_subagent_handler_skips_generations_the_gateway_served(self):
+ client = Mock()
+ handler = SubagentCallbackHandler(client, distinct_id="user", trace_id="trace-1", parent_span_id=uuid4())
+
+ self.assertEqual(self._captured_events(client, handler, self._result(served=True)), ["$ai_span"])
+
+
+class TestRunnerAIGatewayProduct(BaseTest):
+ @patch("ee.hogai.core.runner.is_cloud", return_value=True)
+ @patch("ee.hogai.core.runner.get_instance_region", return_value="US")
+ @patch("ee.hogai.core.runner.get_client", return_value=Mock())
+ def test_config_names_the_product_the_root_model_routes_for(self, _mock_get_client, _mock_region, _mock_is_cloud):
+ for conversation_type, expected_product in [
+ (Conversation.Type.ASSISTANT, "posthog_ai"),
+ (Conversation.Type.TOOL_CALL, "mcp"),
+ ]:
+ with self.subTest(conversation_type=conversation_type):
+ conversation = Conversation.objects.create(team=self.team, user=self.user, type=conversation_type)
+ runner = ChatAgentRunner(team=self.team, conversation=conversation, user=self.user)
+
+ self.assertEqual(runner._get_config()["configurable"]["ai_product"], expected_product)
+ handler = runner._callback_handlers[0]
+ assert isinstance(handler, MaxCallbackHandler)
+ self.assertEqual((handler._properties or {}).get("ai_product"), expected_product)
+
+ @patch("ee.hogai.core.runner.is_cloud", return_value=True)
+ @patch("ee.hogai.core.runner.get_instance_region", return_value="US")
+ @patch("ee.hogai.core.runner.get_client", return_value=Mock())
+ def test_config_carries_the_privacy_mode_the_handler_redacts_with(
+ self, _mock_get_client, _mock_region, _mock_is_cloud
+ ):
+ conversation = Conversation.objects.create(team=self.team, user=self.user, type=Conversation.Type.ASSISTANT)
+ for enabled in (True, False):
+ with (
+ self.subTest(privacy_mode=enabled),
+ patch("ee.hogai.core.runner.is_privacy_mode_enabled", return_value=enabled),
+ ):
+ runner = ChatAgentRunner(team=self.team, conversation=conversation, user=self.user)
+
+ self.assertIs(runner._get_config()["configurable"]["privacy_mode"], enabled)
+ handler = runner._callback_handlers[0]
+ assert isinstance(handler, MaxCallbackHandler)
+ self.assertIs(handler._privacy_mode, enabled)
+
+ @patch("ee.hogai.core.runner.is_cloud", return_value=True)
+ @patch("ee.hogai.core.runner.get_instance_region", return_value="US")
+ @patch("ee.hogai.core.runner.get_client", return_value=Mock())
+ def test_config_carries_impersonation_for_gateway_rows(self, _mock_get_client, _mock_region, _mock_is_cloud):
+ conversation = Conversation.objects.create(team=self.team, user=self.user, type=Conversation.Type.ASSISTANT)
+ for is_impersonated in (True, False):
+ with self.subTest(is_impersonated=is_impersonated):
+ runner = ChatAgentRunner(
+ team=self.team, conversation=conversation, user=self.user, is_impersonated=is_impersonated
+ )
+
+ self.assertIs(runner._get_config()["configurable"]["is_impersonated"], is_impersonated)
diff --git a/ee/hogai/llm.py b/ee/hogai/llm.py
index 03ba2fc9dd16..0b4710547b6a 100644
--- a/ee/hogai/llm.py
+++ b/ee/hogai/llm.py
@@ -1,5 +1,7 @@
import datetime
from collections.abc import ( # noqa: F401 — Sequence resolves inherited langchain field annotations lazily in this namespace
+ AsyncIterator,
+ Iterator,
Mapping,
Sequence,
)
@@ -9,29 +11,46 @@ from typing import Any, ClassVar, cast
from django.conf import settings
import pytz
+import httpx
import anthropic
import structlog
from asgiref.sync import sync_to_async
from langchain_anthropic import ChatAnthropic
+from langchain_core.callbacks import AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun
from langchain_core.messages import BaseMessage, SystemMessage
-from langchain_core.outputs import LLMResult
+from langchain_core.outputs import ChatGenerationChunk, ChatResult, LLMResult
from langchain_core.prompts import SystemMessagePromptTemplate
from langchain_core.runnables import ensure_config
from langchain_openai import ChatOpenAI
from prometheus_client import Counter
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
+from posthog.llm.gateway_client import AIGatewayConfig, ai_gateway_headers, anthropic_gateway_base_url
from posthog.models import Team, User
from posthog.settings import CLOUD_DEPLOYMENT
logger = structlog.get_logger(__name__)
+POSTHOG_AI_PRODUCT = "posthog_ai"
+
BILLING_SKIPPED_COUNTER = Counter(
"posthog_ai_billing_skipped_total",
"Number of AI generations where billing was skipped due to workflow-level override (e.g., impersonation)",
["model"],
)
+AI_GATEWAY_FALLBACK_COUNTER = Counter(
+ "posthog_ai_gateway_fallback_total",
+ "PostHog AI model calls that fell back from the Go ai-gateway to the direct provider",
+ ["reason"],
+)
+
+AI_GATEWAY_TIMEOUT = httpx.Timeout(150.0, connect=10.0, write=15.0, pool=5.0)
+"""Above the gateway's 120s stream idle close. Nothing heartbeats while the gateway stalls, so every phase is bounded
+to leave the twin time inside the 300s activity heartbeat."""
+
+AI_GATEWAY_SERVED_KEY = "ai_gateway_served"
+
PROJECT_ORG_USER_CONTEXT_PROMPT = """
You are currently in project {{{project_name}}}, which is part of the {{{organization_name}}} organization.
The user's name appears to be {{{user_full_name}}} ({{{user_email}}}). Feel free to use their first name when greeting. DO NOT use this name if it appears possibly fake.
@@ -60,6 +79,77 @@ OPENAI_FLEX_MODELS = ["o3", "o4-mini", "gpt5", "gpt5-mini", "gpt5-nano"]
_BYPASS_PROXY_MOUNTS: dict[str, None] = {"http://": None, "https://": None, "all://": None}
+def is_ai_gateway_served(output: object) -> bool:
+ if not isinstance(output, LLMResult):
+ return False
+ return any(
+ (generation.generation_info or {}).get(AI_GATEWAY_SERVED_KEY)
+ for generations in output.generations
+ for generation in generations
+ )
+
+
+# Anthropic's wording for a billing or usage-limit block; the gateway classifies on the same list.
+_PROVIDER_BILLING_SIGNATURES = ("credit balance", "usage limit", "regain access", "plans & billing")
+
+
+def _is_provider_billing_block(error: anthropic.APIStatusError) -> bool:
+ """Anthropic blocking the gateway's workspace, passed through; the gateway's own 402s carry X-PostHog-Denial."""
+ if error.status_code not in (400, 402) or error.response.headers.get("X-PostHog-Denial"):
+ return False
+ detail = error.body.get("error") if isinstance(error.body, dict) else None
+ if not isinstance(detail, dict):
+ return False
+ message = str(detail.get("message") or "").lower()
+ return detail.get("type") == "billing_error" or any(sig in message for sig in _PROVIDER_BILLING_SIGNATURES)
+
+
+def _carries_output(chunk: ChatGenerationChunk) -> bool:
+ """Thinking counts: the user sees it stream. An opening metadata chunk does not."""
+ return bool(chunk.message.content) or bool(getattr(chunk.message, "tool_call_chunks", None))
+
+
+def _marked_as_gateway_served(chunks: list[ChatGenerationChunk]) -> list[ChatGenerationChunk]:
+ """One marked chunk marks the merged generation, which the SDK callback then skips."""
+ first = chunks[0]
+ first.generation_info = {**(first.generation_info or {}), AI_GATEWAY_SERVED_KEY: True}
+ return chunks
+
+
+def _ai_gateway_fallback_reason(error: Exception) -> str | None:
+ """None re-raises: a direct retry cannot fix other errors, and the gateway's own 402/403 must stay binding."""
+ if isinstance(error, anthropic.APITimeoutError):
+ return "timeout"
+ if isinstance(error, anthropic.APIConnectionError):
+ return "connection"
+ if isinstance(error, anthropic.APIStatusError):
+ if error.status_code == 401:
+ return "unauthorized"
+ if error.status_code == 429:
+ return "rate_limited"
+ if error.status_code >= 500:
+ return "server_error"
+ if _is_provider_billing_block(error):
+ return "provider_billing"
+ return None
+
+
+def _has_ai_gateway_headers(kwargs: Mapping[str, Any]) -> bool:
+ return "X-PostHog-Product" in (kwargs.get("extra_headers") or {})
+
+
+def _without_ai_gateway_headers(kwargs: Mapping[str, Any]) -> dict[str, Any]:
+ new_kwargs = {key: value for key, value in kwargs.items() if key != "extra_headers"}
+ extra_headers = {
+ name: value
+ for name, value in (kwargs.get("extra_headers") or {}).items()
+ if not name.lower().startswith("x-posthog-")
+ }
+ if extra_headers:
+ new_kwargs["extra_headers"] = extra_headers
+ return new_kwargs
+
+
class MaxChatMixin(BaseModel):
# We don't want to validate Django models here.
model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -175,7 +265,7 @@ class MaxChatMixin(BaseModel):
posthog_props = dict(self.posthog_properties or {})
posthog_props["$ai_billable"] = self._get_effective_billable()
posthog_props["team_id"] = self.team.id
- posthog_props.setdefault("ai_product", "posthog_ai")
+ posthog_props.setdefault("ai_product", POSTHOG_AI_PRODUCT)
metadata.setdefault("ls_provider", self.posthog_provider)
metadata["posthog_properties"] = posthog_props
@@ -265,6 +355,31 @@ class MaxChatAnthropic(MaxChatMixin, ChatAnthropic):
If True, bypasses egress proxies (HTTP_PROXY/etc)—use for private LLM gateway; if False, default behavior.
"""
+ ai_gateway_fallback: ChatAnthropic | None = Field(default=None, exclude=True)
+ """Direct twin that serves calls which must not route, and gateway failures before any output."""
+
+ @classmethod
+ def via_ai_gateway(cls, ai_gateway: AIGatewayConfig, **kwargs: Any) -> "MaxChatAnthropic":
+ return cls(
+ **{
+ **kwargs,
+ "anthropic_api_url": anthropic_gateway_base_url(ai_gateway.url),
+ "anthropic_api_key": ai_gateway.api_key,
+ "bypass_proxy": True,
+ # The twin is the retry; an SDK retry doubles the wait before it.
+ "max_retries": 0,
+ "ai_gateway_fallback": cls(**kwargs),
+ }
+ )
+
+ @cached_property
+ def _client_params(self) -> dict[str, Any]:
+ params = cast(dict[str, Any], ChatAnthropic._client_params.func(self)) # type: ignore[attr-defined]
+ if self.ai_gateway_fallback is not None:
+ # langchain-anthropic defaults to no timeout, so a stalled gateway would never fall back.
+ params["timeout"] = AI_GATEWAY_TIMEOUT
+ return params
+
@cached_property
def _client(self) -> anthropic.Client:
if not self.bypass_proxy:
@@ -303,6 +418,173 @@ class MaxChatAnthropic(MaxChatMixin, ChatAnthropic):
kwargs["timeout"] = client_params["timeout"]
return kwargs
+ def _routes_via_ai_gateway(self) -> bool:
+ """Other products keep their capture and billing on the direct path."""
+ if self.ai_gateway_fallback is None:
+ return False
+ configurable = ensure_config().get("configurable") or {}
+ return (
+ configurable.get("ai_product") == POSTHOG_AI_PRODUCT
+ and (self.posthog_properties or {}).get("ai_product", POSTHOG_AI_PRODUCT) == POSTHOG_AI_PRODUCT
+ )
+
+ def _with_ai_gateway_headers(self, kwargs: dict[str, Any]) -> dict[str, Any]:
+ configurable = ensure_config().get("configurable") or {}
+ posthog_properties = kwargs["metadata"]["posthog_properties"]
+ trace_id = str(configurable["trace_id"]) if configurable.get("trace_id") else None
+ conversation_id = str(configurable["thread_id"]) if configurable.get("thread_id") else None
+ # The gateway strips `$` keys and stamps ai_product itself; team_id names the customer it bills.
+ labels = {
+ key: str(value)
+ for key, value in posthog_properties.items()
+ if value is not None and not key.startswith("$") and key != "ai_product"
+ }
+ if conversation_id:
+ labels["conversation_id"] = conversation_id
+ # Support-trace filters read this property, which the SDK handler sets only on its own events.
+ if configurable.get("is_impersonated"):
+ labels["ai_support_impersonated"] = "true"
+ headers = (
+ ai_gateway_headers(
+ ai_product=POSTHOG_AI_PRODUCT,
+ trace_id=trace_id,
+ session_id=conversation_id,
+ properties=labels,
+ distinct_id=configurable.get("distinct_id") or self.user.distinct_id,
+ )
+ or {}
+ )
+ if not posthog_properties["$ai_billable"]:
+ headers["X-PostHog-Billable"] = "false"
+ # The gateway records prompts and outputs unless asked not to, so an unknown privacy mode redacts too.
+ if configurable.get("privacy_mode") is not False:
+ headers["X-PostHog-Privacy-Mode"] = "true"
+ return {**kwargs, "extra_headers": {**(kwargs.get("extra_headers") or {}), **headers}}
+
+ def _record_ai_gateway_fallback(self, reason: str, error: Exception) -> None:
+ AI_GATEWAY_FALLBACK_COUNTER.labels(reason=reason).inc()
+ logger.warning("posthog_ai_gateway_fallback", reason=reason, error_type=type(error).__name__, model=self.model)
+
+ def get_num_tokens_from_messages(self, messages: list[BaseMessage], tools: Any = None, **kwargs: Any) -> int:
+ # Token counts have no fallback, so a gateway 429 here would fail the turn.
+ if self.ai_gateway_fallback is not None:
+ return self.ai_gateway_fallback.get_num_tokens_from_messages(messages, tools=tools, **kwargs)
+ return super().get_num_tokens_from_messages(messages, tools=tools, **kwargs)
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ # Sync calls stay direct: only `agenerate` adds the gateway headers.
+ if self.ai_gateway_fallback is not None:
+ return self.ai_gateway_fallback._stream(
+ messages,
+ stop=stop,
+ run_manager=run_manager,
+ stream_usage=stream_usage,
+ **_without_ai_gateway_headers(kwargs),
+ )
+ return super()._stream(messages, stop=stop, run_manager=run_manager, stream_usage=stream_usage, **kwargs)
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.ai_gateway_fallback is not None:
+ return self.ai_gateway_fallback._generate(
+ messages, stop=stop, run_manager=run_manager, **_without_ai_gateway_headers(kwargs)
+ )
+ return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
+
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ fallback = self.ai_gateway_fallback
+ if fallback is None:
+ async for chunk in super()._astream(
+ messages, stop=stop, run_manager=run_manager, stream_usage=stream_usage, **kwargs
+ ):
+ yield chunk
+ return
+
+ direct_kwargs = _without_ai_gateway_headers(kwargs)
+ if _has_ai_gateway_headers(kwargs):
+ served = False
+ # Anthropic opens the stream with a metadata chunk. Holding those keeps the fallback open until real
+ # output, and keeps their usage off the twin's generation.
+ held: list[ChatGenerationChunk] = []
+ try:
+ async for chunk in super()._astream(
+ messages, stop=stop, run_manager=run_manager, stream_usage=stream_usage, **kwargs
+ ):
+ if served:
+ yield chunk
+ continue
+ held.append(chunk)
+ if not _carries_output(chunk):
+ continue
+ served = True
+ for pending in _marked_as_gateway_served(held):
+ yield pending
+ if not served and held:
+ # A stream that ended without output was still served by the gateway.
+ for pending in _marked_as_gateway_served(held):
+ yield pending
+ return
+ except Exception as error:
+ reason = _ai_gateway_fallback_reason(error)
+ # After output the user has seen the turn, so a direct retry would repeat it.
+ if served or reason is None:
+ raise
+ self._record_ai_gateway_fallback(reason, error)
+
+ async for chunk in fallback._astream(
+ messages, stop=stop, run_manager=run_manager, stream_usage=stream_usage, **direct_kwargs
+ ):
+ yield chunk
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ fallback = self.ai_gateway_fallback
+ # A streaming call resolves through `_astream`, which routes and falls back on its own.
+ if fallback is None or self.streaming:
+ return await super()._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs)
+
+ direct_kwargs = _without_ai_gateway_headers(kwargs)
+ if _has_ai_gateway_headers(kwargs):
+ try:
+ result = await super()._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs)
+ except Exception as error:
+ reason = _ai_gateway_fallback_reason(error)
+ if reason is None:
+ raise
+ self._record_ai_gateway_fallback(reason, error)
+ else:
+ for generation in result.generations:
+ generation.generation_info = {**(generation.generation_info or {}), AI_GATEWAY_SERVED_KEY: True}
+ return result
+
+ return await fallback._agenerate(messages, stop=stop, run_manager=run_manager, **direct_kwargs)
+
def generate(
self,
messages: list[list[BaseMessage]],
@@ -328,5 +610,7 @@ class MaxChatAnthropic(MaxChatMixin, ChatAnthropic):
messages = self._enrich_messages(messages, project_org_user_variables)
kwargs = self._with_posthog_properties(kwargs)
+ if self._routes_via_ai_gateway():
+ kwargs = self._with_ai_gateway_headers(kwargs)
return await super().agenerate(messages, *args, **kwargs)
diff --git a/ee/hogai/test/test_llm.py b/ee/hogai/test/test_llm.py
index 35a931245738..267d3c6487e3 100644
--- a/ee/hogai/test/test_llm.py
+++ b/ee/hogai/test/test_llm.py
@@ -1,4 +1,5 @@
import re
+import json
from datetime import datetime
from functools import cached_property
from pathlib import Path
@@ -8,15 +9,27 @@ from unittest.mock import patch
from django.test import SimpleTestCase
+import httpx
import anthropic
from langchain_anthropic import ChatAnthropic
-from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
-from langchain_core.outputs import ChatGeneration, Generation, LLMResult
+from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage, HumanMessage, SystemMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, Generation, LLMResult
from parameterized import parameterized
+from posthog.llm.gateway_client import AIGatewayConfig
from posthog.settings import BASE_DIR
+from posthog.temporal.ai.chat_agent import CHAT_AGENT_ACTIVITY_HEARTBEAT_TIMEOUT
-from ee.hogai.llm import BILLING_SKIPPED_COUNTER, PROJECT_ORG_USER_CONTEXT_PROMPT, MaxChatAnthropic, MaxChatOpenAI
+from ee.hogai.llm import (
+ AI_GATEWAY_FALLBACK_COUNTER,
+ AI_GATEWAY_SERVED_KEY,
+ AI_GATEWAY_TIMEOUT,
+ BILLING_SKIPPED_COUNTER,
+ PROJECT_ORG_USER_CONTEXT_PROMPT,
+ MaxChatAnthropic,
+ MaxChatOpenAI,
+ is_ai_gateway_served,
+)
@patch.dict("os.environ", {"OPENAI_API_KEY": "test-api-key", "ANTHROPIC_API_KEY": "test-api-key"})
@@ -609,3 +622,429 @@ class TestProjectOrgUserContextPrompt(SimpleTestCase):
"The prompt names settings sections that don't resolve, so the assistant will link users "
'to "Setting not found" pages. Valid IDs come from frontend/src/scenes/settings/SettingsMap.tsx.',
)
+
+
+def _anthropic_message_body(text: str) -> dict:
+ return {
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-6",
+ "content": [{"type": "text", "text": text}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 3, "output_tokens": 2},
+ }
+
+
+def _usage(input_tokens: int) -> dict[str, int]:
+ return {"input_tokens": input_tokens, "output_tokens": 1, "total_tokens": input_tokens + 1}
+
+
+def _anthropic_error(
+ status: int, error_type: str = "api_error", message: str = "failed", headers: dict[str, str] | None = None
+) -> httpx.Response:
+ return httpx.Response(
+ status, headers=headers, json={"type": "error", "error": {"type": error_type, "message": message}}
+ )
+
+
+_WORKSPACE_LIMIT = "You have reached your specified workspace API usage limits. You will regain access on 2026-10-01."
+
+
[email protected]("os.environ", {"ANTHROPIC_API_KEY": "direct-api-key"})
+class TestMaxChatAnthropicAIGateway(BaseTest):
+ gateway = AIGatewayConfig(url="https://ai-gateway.test/v1", api_key="phs_gateway")
+
+ def setUp(self):
+ super().setUp()
+ self.requests: list[httpx.Request] = []
+ self.gateway_outcome: httpx.Response | Exception = httpx.Response(200, json=_anthropic_message_body("gateway"))
+
+ def _respond(self, request: httpx.Request) -> httpx.Response:
+ self.requests.append(request)
+ if request.url.host != "ai-gateway.test":
+ return httpx.Response(200, json=_anthropic_message_body("direct"))
+ if isinstance(self.gateway_outcome, Exception):
+ raise self.gateway_outcome
+ return self.gateway_outcome
+
+ def _model(self, **kwargs) -> MaxChatAnthropic:
+ model = MaxChatAnthropic.via_ai_gateway(
+ self.gateway,
+ model="claude-sonnet-4-6",
+ user=self.user,
+ team=self.team,
+ inject_context=False,
+ billable=True,
+ posthog_properties={"agent_mode": "sql", "supermode": None},
+ **kwargs,
+ )
+ transport = httpx.MockTransport(self._respond)
+ for target in (model, model.ai_gateway_fallback):
+ assert target is not None
+ params = {**target._client_params, "max_retries": 0}
+ target.__dict__["_client"] = anthropic.Client(**params, http_client=httpx.Client(transport=transport))
+ target.__dict__["_async_client"] = anthropic.AsyncClient(
+ **params, http_client=httpx.AsyncClient(transport=transport)
+ )
+ return model
+
+ def _direct_host(self, model: MaxChatAnthropic) -> str:
+ assert model.ai_gateway_fallback is not None
+ return httpx.URL(model.ai_gateway_fallback.anthropic_api_url or "").host
+
+ def _config(self, **configurable) -> dict:
+ return {
+ "configurable": {
+ "trace_id": "trace-1",
+ "thread_id": "conversation-1",
+ "distinct_id": "distinct-1",
+ "ai_product": "posthog_ai",
+ "privacy_mode": False,
+ "is_agent_billable": True,
+ **configurable,
+ }
+ }
+
+ def _fake_astream(
+ self,
+ calls: list[str],
+ gateway_chunks: int,
+ gateway_raises: bool,
+ metadata_chunks: int = 0,
+ tool_chunk: bool = False,
+ ):
+ """`metadata_chunks` stand in for Anthropic's opening message-start chunk: usage, no output."""
+
+ async def _astream(model, messages, stop=None, run_manager=None, **kwargs):
+ if model.ai_gateway_fallback is None:
+ calls.append("direct")
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content="direct", usage_metadata=_usage(3)),
+ )
+ return
+ calls.append("gateway")
+ for _ in range(metadata_chunks):
+ yield ChatGenerationChunk(message=AIMessageChunk(content="", usage_metadata=_usage(7)))
+ if tool_chunk:
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(
+ content="",
+ tool_call_chunks=[
+ {"name": "query", "args": "{}", "id": "toolu_1", "index": 0, "type": "tool_call_chunk"}
+ ],
+ )
+ )
+ for _ in range(gateway_chunks):
+ yield ChatGenerationChunk(message=AIMessageChunk(content="gateway"))
+ if gateway_raises:
+ raise anthropic.APIConnectionError(request=httpx.Request("POST", "https://ai-gateway.test/v1/messages"))
+
+ return _astream
+
+ def test_via_ai_gateway_targets_the_gateway_and_keeps_a_direct_twin(self):
+ model = MaxChatAnthropic.via_ai_gateway(self.gateway, model="claude-sonnet-4-6", user=self.user, team=self.team)
+ twin = model.ai_gateway_fallback
+
+ self.assertEqual(model.anthropic_api_url, "https://ai-gateway.test")
+ self.assertEqual(model.anthropic_api_key.get_secret_value(), "phs_gateway")
+ self.assertTrue(model.bypass_proxy)
+ self.assertEqual(model.max_retries, 0)
+ assert isinstance(twin, MaxChatAnthropic)
+ self.assertNotIn("ai-gateway.test", twin.anthropic_api_url or "")
+ self.assertEqual(twin.anthropic_api_key.get_secret_value(), "direct-api-key")
+ self.assertFalse(twin.bypass_proxy)
+ self.assertEqual(twin.max_retries, 3)
+ self.assertIsNone(twin.ai_gateway_fallback)
+
+ async def test_routed_call_sends_gateway_attribution_headers(self):
+ cases: list[tuple[bool, bool, str | None, dict[str, str]]] = [
+ (True, False, None, {}),
+ (False, False, "false", {}),
+ (False, True, "false", {"ai_support_impersonated": "true"}),
+ ]
+ for is_agent_billable, is_impersonated, billable_header, impersonation_props in cases:
+ with self.subTest(is_agent_billable=is_agent_billable, is_impersonated=is_impersonated):
+ self.requests.clear()
+ model = self._model()
+ config = self._config(is_agent_billable=is_agent_billable, is_impersonated=is_impersonated)
+ with patch("ee.hogai.llm.ensure_config", return_value=config):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(
+ [str(request.url) for request in self.requests], ["https://ai-gateway.test/v1/messages"]
+ )
+ headers = self.requests[0].headers
+ self.assertEqual(headers["x-api-key"], "phs_gateway")
+ self.assertEqual(headers["x-posthog-product"], "posthog_ai")
+ self.assertEqual(headers["x-posthog-trace-id"], "trace-1")
+ self.assertEqual(headers["x-posthog-session-id"], "conversation-1")
+ self.assertEqual(headers["x-posthog-distinct-id"], "distinct-1")
+ self.assertEqual(
+ json.loads(headers["x-posthog-properties"]),
+ {
+ "agent_mode": "sql",
+ "team_id": str(self.team.id),
+ "conversation_id": "conversation-1",
+ "ai_product": "posthog_ai",
+ **impersonation_props,
+ },
+ )
+ self.assertEqual(headers.get("x-posthog-billable"), billable_header)
+ self.assertTrue(is_ai_gateway_served(result))
+
+ async def test_privacy_mode_routes_with_the_redaction_header(self):
+ for privacy_mode, redaction_header in [(False, None), (True, "true"), (None, "true")]:
+ with self.subTest(privacy_mode=privacy_mode):
+ self.requests.clear()
+ model = self._model()
+ with patch("ee.hogai.llm.ensure_config", return_value=self._config(privacy_mode=privacy_mode)):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual([request.url.host for request in self.requests], ["ai-gateway.test"])
+ self.assertEqual(self.requests[0].headers.get("x-posthog-privacy-mode"), redaction_header)
+ self.assertTrue(is_ai_gateway_served(result))
+
+ async def test_calls_for_other_products_go_direct(self):
+ cases: list[tuple[str, dict, dict | None]] = [
+ ("mcp conversation", self._config(ai_product="mcp"), None),
+ ("outside a posthog_ai run", self._config(ai_product=None), None),
+ ("product override", self._config(), {"ai_product": "alert_investigation_agent"}),
+ ]
+ for name, config, posthog_properties in cases:
+ with self.subTest(name):
+ self.requests.clear()
+ model = self._model()
+ if posthog_properties:
+ model.posthog_properties = posthog_properties
+ with patch("ee.hogai.llm.ensure_config", return_value=config):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual([request.url.host for request in self.requests], [self._direct_host(model)])
+ self.assertFalse(any(header.lower().startswith("x-posthog-") for header in self.requests[0].headers))
+ self.assertFalse(is_ai_gateway_served(result))
+
+ async def test_retryable_gateway_failures_fall_back_to_the_direct_twin(self):
+ request = httpx.Request("POST", "https://ai-gateway.test/v1/messages")
+ cases: list[tuple[str, httpx.Response | Exception]] = [
+ ("connection", httpx.ConnectError("refused", request=request)),
+ ("timeout", httpx.ReadTimeout("slow", request=request)),
+ ("unauthorized", _anthropic_error(401)),
+ ("rate_limited", _anthropic_error(429)),
+ ("server_error", _anthropic_error(503)),
+ ("server_error", _anthropic_error(529)),
+ ("provider_billing", _anthropic_error(400, "invalid_request_error", _WORKSPACE_LIMIT)),
+ ("provider_billing", _anthropic_error(402, "billing_error", "Payment required")),
+ ]
+ for reason, outcome in cases:
+ with self.subTest(reason=reason, outcome=outcome):
+ self.requests.clear()
+ self.gateway_outcome = outcome
+ model = self._model()
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(AI_GATEWAY_FALLBACK_COUNTER, "labels") as mock_labels,
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(
+ [request.url.host for request in self.requests], ["ai-gateway.test", self._direct_host(model)]
+ )
+ direct_headers = self.requests[1].headers
+ self.assertEqual(direct_headers["x-api-key"], "direct-api-key")
+ self.assertFalse(any(header.lower().startswith("x-posthog-") for header in direct_headers))
+ self.assertEqual(result.generations[0][0].text, "direct")
+ self.assertFalse(is_ai_gateway_served(result))
+ mock_labels.assert_called_once_with(reason=reason)
+
+ async def test_non_retryable_gateway_failures_raise_without_fallback(self):
+ cases: list[tuple[str, httpx.Response]] = [
+ ("bad request", _anthropic_error(400, "invalid_request_error", "prompt is too long")),
+ (
+ "gateway's own credit denial",
+ _anthropic_error(402, "billing_error", _WORKSPACE_LIMIT, {"X-PostHog-Denial": "insufficient_credits"}),
+ ),
+ ("forbidden", _anthropic_error(403)),
+ ("not found", _anthropic_error(404)),
+ ]
+ for name, outcome in cases:
+ with self.subTest(name):
+ self.requests.clear()
+ self.gateway_outcome = outcome
+ model = self._model()
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(AI_GATEWAY_FALLBACK_COUNTER, "labels") as mock_labels,
+ self.assertRaises(Exception),
+ ):
+ await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual([request.url.host for request in self.requests], ["ai-gateway.test"])
+ mock_labels.assert_not_called()
+
+ async def test_streaming_gateway_success_marks_the_generation(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(ChatAnthropic, "_astream", self._fake_astream(calls, gateway_chunks=2, gateway_raises=False)),
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway"])
+ self.assertEqual(result.generations[0][0].text, "gatewaygateway")
+ self.assertTrue(is_ai_gateway_served(result))
+
+ async def test_streaming_falls_back_when_the_gateway_fails_before_any_chunk(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(ChatAnthropic, "_astream", self._fake_astream(calls, gateway_chunks=0, gateway_raises=True)),
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway", "direct"])
+ self.assertEqual(result.generations[0][0].text, "direct")
+ self.assertFalse(is_ai_gateway_served(result))
+
+ async def test_streaming_does_not_fall_back_after_a_chunk(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(ChatAnthropic, "_astream", self._fake_astream(calls, gateway_chunks=1, gateway_raises=True)),
+ self.assertRaises(anthropic.APIConnectionError),
+ ):
+ await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway"])
+
+ async def test_streaming_falls_back_after_an_output_free_metadata_chunk(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(
+ ChatAnthropic,
+ "_astream",
+ self._fake_astream(calls, gateway_chunks=0, gateway_raises=True, metadata_chunks=1),
+ ),
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway", "direct"])
+ self.assertEqual(result.generations[0][0].text, "direct")
+ self.assertFalse(is_ai_gateway_served(result))
+ # The held chunk is dropped, so the gateway's usage does not land on the twin's generation.
+ generation = result.generations[0][0]
+ assert isinstance(generation, ChatGeneration) and isinstance(generation.message, AIMessage)
+ message = generation.message
+ assert message.usage_metadata is not None
+ self.assertEqual(message.usage_metadata["input_tokens"], 3)
+
+ async def test_streaming_marks_the_generation_when_output_follows_a_metadata_chunk(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(
+ ChatAnthropic,
+ "_astream",
+ self._fake_astream(calls, gateway_chunks=1, gateway_raises=False, metadata_chunks=1),
+ ),
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway"])
+ self.assertEqual(result.generations[0][0].text, "gateway")
+ self.assertTrue(is_ai_gateway_served(result))
+ generation = result.generations[0][0]
+ assert isinstance(generation, ChatGeneration) and isinstance(generation.message, AIMessage)
+ message = generation.message
+ assert message.usage_metadata is not None
+ self.assertEqual(message.usage_metadata["input_tokens"], 7)
+
+ async def test_streaming_does_not_fall_back_after_a_tool_call_chunk(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(
+ ChatAnthropic,
+ "_astream",
+ self._fake_astream(calls, gateway_chunks=0, gateway_raises=True, metadata_chunks=1, tool_chunk=True),
+ ),
+ self.assertRaises(anthropic.APIConnectionError),
+ ):
+ await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway"])
+
+ async def test_streaming_marks_a_gateway_stream_that_produced_no_output(self):
+ calls: list[str] = []
+ model = self._model(streaming=True)
+ with (
+ patch("ee.hogai.llm.ensure_config", return_value=self._config()),
+ patch.object(
+ ChatAnthropic,
+ "_astream",
+ self._fake_astream(calls, gateway_chunks=0, gateway_raises=False, metadata_chunks=1),
+ ),
+ ):
+ result = await model.agenerate([[HumanMessage(content="hello")]])
+
+ self.assertEqual(calls, ["gateway"])
+ self.assertEqual(result.generations[0][0].text, "")
+ self.assertTrue(is_ai_gateway_served(result))
+
+ def test_gateway_client_has_a_bounded_timeout(self):
+ model = MaxChatAnthropic.via_ai_gateway(self.gateway, model="claude-sonnet-4-6", user=self.user, team=self.team)
+ twin = model.ai_gateway_fallback
+ assert twin is not None
+
+ for client in (model._client, model._async_client):
+ self.assertEqual(client.timeout, AI_GATEWAY_TIMEOUT)
+ self.assertEqual(client._client.timeout, AI_GATEWAY_TIMEOUT)
+ self.assertEqual(client.max_retries, 0)
+ self.assertIsNone(twin._client_params["timeout"])
+
+ phases = [
+ AI_GATEWAY_TIMEOUT.connect,
+ AI_GATEWAY_TIMEOUT.read,
+ AI_GATEWAY_TIMEOUT.write,
+ AI_GATEWAY_TIMEOUT.pool,
+ ]
+ self.assertNotIn(None, phases)
+ stalled_gateway_seconds = sum(phase or 0.0 for phase in phases) * (model.max_retries + 1)
+ self.assertGreaterEqual(CHAT_AGENT_ACTIVITY_HEARTBEAT_TIMEOUT - stalled_gateway_seconds, 120)
+
+ def test_token_counting_uses_the_direct_twin(self):
+ model = MaxChatAnthropic.via_ai_gateway(self.gateway, model="claude-sonnet-4-6", user=self.user, team=self.team)
+
+ def count(counting_model, messages, tools=None, **kwargs):
+ return 0 if counting_model.ai_gateway_fallback is not None else 7
+
+ with patch.object(ChatAnthropic, "get_num_tokens_from_messages", count):
+ self.assertEqual(model.get_num_tokens_from_messages([HumanMessage(content="hello")]), 7)
+
+ def test_sync_calls_use_the_direct_twin(self):
+ model = self._model()
+ with patch("ee.hogai.llm.ensure_config", return_value=self._config()):
+ result = model.generate([[HumanMessage(content="hello")]])
+
+ self.assertEqual([request.url.host for request in self.requests], [self._direct_host(model)])
+ self.assertFalse(is_ai_gateway_served(result))
+
+ def test_is_ai_gateway_served_reads_the_generation_marker(self):
+ served = LLMResult(
+ generations=[
+ [ChatGeneration(message=AIMessage(content="hi"), generation_info={AI_GATEWAY_SERVED_KEY: True})]
+ ]
+ )
+ unmarked = LLMResult(generations=[[ChatGeneration(message=AIMessage(content="hi"))]])
+
+ self.assertTrue(is_ai_gateway_served(served))
+ self.assertFalse(is_ai_gateway_served(unmarked))
+ self.assertFalse(is_ai_gateway_served(ValueError("failed")))
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index af375772b37c..f3990ab3cfa0 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -338,7 +338,7 @@ def team_trace_id(team_id: int | None) -> str | None:
return str(uuid5(_TEAM_TRACE_ID_NAMESPACE, f"team-{team_id}"))
-def _anthropic_gateway_base_url(openai_base_url: str) -> str:
+def anthropic_gateway_base_url(openai_base_url: str) -> str:
"""Drop the OpenAI ``/v1`` suffix so the Anthropic SDK, which appends ``/v1/messages``
itself, hits the same gateway root the OpenAI route uses. ``resolve_ai_gateway_config``
guarantees the ``/v1`` suffix, so this is the inverse of that validation.
@@ -451,7 +451,7 @@ def build_async_anthropic_client(
}
return AsyncAnthropic(
api_key=gateway.api_key,
- base_url=_anthropic_gateway_base_url(gateway.url),
+ base_url=anthropic_gateway_base_url(gateway.url),
default_headers=ai_gateway_headers(
ai_product=ai_product,
trace_id=team_trace_id(team_id),
@@ -475,7 +475,7 @@ def _ai_gateway_anthropic_client(
labels["team_id"] = str(team_id)
return Anthropic(
api_key=gateway.api_key,
- base_url=_anthropic_gateway_base_url(gateway.url),
+ base_url=anthropic_gateway_base_url(gateway.url),
default_headers=ai_gateway_headers(
ai_product=ai_product,
trace_id=trace_id or team_trace_id(team_id),