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.

fix(aio): preserve metadata and validate failed LLM responses (#79501)

Richard Solomou04e47a78e417
diff --git a/ee/hogai/llm.py b/ee/hogai/llm.py
index 3c76ddc0cf2a..03ba2fc9dd16 100644
--- a/ee/hogai/llm.py
+++ b/ee/hogai/llm.py
@@ -4,7 +4,7 @@ from collections.abc import ( # noqa: F401 — Sequence resolves inherited lang
Sequence,
)
from functools import cached_property
-from typing import Any, cast
+from typing import Any, ClassVar, cast
from django.conf import settings
@@ -86,6 +86,7 @@ class MaxChatMixin(BaseModel):
Additional PostHog properties to be added to the $ai_generation event.
These will be merged with the standard properties like $ai_billable and team_id.
"""
+ posthog_provider: ClassVar[str]
def model_post_init(self, __context: Any) -> None:
if self.max_retries is None:
@@ -176,6 +177,7 @@ class MaxChatMixin(BaseModel):
posthog_props["team_id"] = self.team.id
posthog_props.setdefault("ai_product", "posthog_ai")
+ metadata.setdefault("ls_provider", self.posthog_provider)
metadata["posthog_properties"] = posthog_props
new_kwargs["metadata"] = metadata
@@ -191,6 +193,8 @@ class MaxChatOpenAI(MaxChatMixin, ChatOpenAI):
If inject_context is set to False, no context will be included in the system prompt.
"""
+ posthog_provider: ClassVar[str] = "openai"
+
def model_post_init(self, __context: Any) -> None:
super().model_post_init(__context)
if settings.IN_EVAL_TESTING and not self.service_tier and self.model_name in OPENAI_FLEX_MODELS:
@@ -254,6 +258,8 @@ class MaxChatAnthropic(MaxChatMixin, ChatAnthropic):
It also makes sure we retry automatically in case of errors.
"""
+ posthog_provider: ClassVar[str] = "anthropic"
+
bypass_proxy: bool = False
"""
If True, bypasses egress proxies (HTTP_PROXY/etc)—use for private LLM gateway; if False, default behavior.
diff --git a/ee/hogai/test/test_llm.py b/ee/hogai/test/test_llm.py
index 08bee77c2a15..35a931245738 100644
--- a/ee/hogai/test/test_llm.py
+++ b/ee/hogai/test/test_llm.py
@@ -21,6 +21,19 @@ from ee.hogai.llm import BILLING_SKIPPED_COUNTER, PROJECT_ORG_USER_CONTEXT_PROMP
@patch.dict("os.environ", {"OPENAI_API_KEY": "test-api-key", "ANTHROPIC_API_KEY": "test-api-key"})
class TestMaxChatOpenAI(BaseTest):
+ @parameterized.expand(
+ [
+ ("openai", MaxChatOpenAI, {}, "openai"),
+ ("anthropic", MaxChatAnthropic, {"model": "claude"}, "anthropic"),
+ ]
+ )
+ def test_provider_is_included_in_callback_metadata(self, _name, llm_class, llm_kwargs, expected_provider):
+ llm = llm_class(user=self.user, team=self.team, **llm_kwargs)
+
+ call_kwargs = llm._with_posthog_properties()
+
+ self.assertEqual(call_kwargs["metadata"]["ls_provider"], expected_provider)
+
def setUp(self):
super().setUp()
# Setup test data
diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.py
index 69f779c6b9fc..95253f4759f6 100644
--- a/products/signals/backend/temporal/llm.py
+++ b/products/signals/backend/temporal/llm.py
@@ -5,7 +5,7 @@ from typing import Optional, TypeVar
from django.conf import settings
import structlog
-from anthropic.types import MessageParam
+from anthropic.types import Message, MessageParam
from posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
from posthog.llm.gateway_client import (
@@ -57,8 +57,11 @@ class EmptyLLMResponseError(Exception):
pass
-def _extract_text_content(response) -> str:
+def _extract_text_content(response: Message) -> str:
"""Extract text content from Anthropic response."""
+ if not isinstance(response, Message):
+ raise TypeError(f"Expected Anthropic Message response, got {type(response).__name__}")
+
for block in reversed(response.content):
if block.type == "text":
return block.text
diff --git a/products/signals/backend/test/test_llm.py b/products/signals/backend/test/test_llm.py
index 16d90e66c503..282575351475 100644
--- a/products/signals/backend/test/test_llm.py
+++ b/products/signals/backend/test/test_llm.py
@@ -3,19 +3,23 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.test import override_settings
+from anthropic.types import Message, TextBlock, Usage
+
from products.signals.backend.temporal.llm import call_llm
from products.signals.eval.llm_gen.client import CanonicalSignal, CanonicalSignalBatch, generate_canonical_signals
MODULE_PATH = "products.signals.backend.temporal.llm"
-def _text_response(text: str) -> MagicMock:
- block = MagicMock()
- block.type = "text"
- block.text = text
- response = MagicMock()
- response.content = [block]
- return response
+def _text_response(text: str) -> Message:
+ return Message(
+ id="msg_test",
+ content=[TextBlock(text=text, type="text")],
+ model="claude-sonnet-4-5",
+ role="assistant",
+ type="message",
+ usage=Usage(input_tokens=1, output_tokens=1),
+ )
def _mock_anthropic_client() -> MagicMock:
@@ -78,6 +82,26 @@ async def test_without_ai_product_stays_on_python_gateway_even_with_env_set():
assert client.messages.create.call_args.kwargs["extra_headers"] == {"x-posthog-property-ai_stage": "match"}
+@override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")
+async def test_non_message_response_raises_descriptive_error():
+ client = _mock_anthropic_client()
+ client.messages.create.return_value = "not json"
+
+ with (
+ patch(f"{MODULE_PATH}.build_async_anthropic_client", return_value=client),
+ pytest.raises(TypeError, match="Expected Anthropic Message response, got str"),
+ ):
+ await call_llm(
+ team_id=1,
+ system_prompt="s",
+ user_prompt="u",
+ validate=lambda text: text,
+ stage="match",
+ ai_product="signals_grouping",
+ )
+
+
# `ai_product` is the opt-in switch, not just a label: dropping it from a call site silently
# reverts that site to the Python gateway and unattributes its spend, with no failing call to
# notice. Each site that opts in pins its own tag and stage.