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(llma): tag provider response ids onto eval/tagger exception context (#58975)

Carlos Marchal3c427856989e
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index 0cf20bdb813a..417df7ae8b8c 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -25,6 +25,7 @@ from posthog.temporal.ai_observability.metrics import (
increment_tokens,
)
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.scoped import scoped_temporal
from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
from products.ai_observability.backend.llm.config import get_eval_config
@@ -527,6 +528,7 @@ def _build_errored_trace_result(allows_na: bool) -> LLMJudgeResult:
@temporalio.activity.defn
+@scoped_temporal()
async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:
"""Execute LLM judge to evaluate the target event.
@@ -589,7 +591,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
return key
# Active key exists but is invalid - fail, don't fall back to trial
raise ApplicationError(
- f"Your API key is {key.state}. Please fix or replace it.",
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
{"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
non_retryable=True,
)
@@ -611,7 +613,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
if key.state != LLMProviderKey.State.OK:
raise ApplicationError(
- f"Your API key is {key.state}. Please fix or replace it.",
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
{"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
non_retryable=True,
)
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index 761c41fb321f..6668df7ec0c8 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -16,6 +16,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.run_evaluation import extract_event_io
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.scoped import scoped_temporal
from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
from products.ai_observability.backend.llm.config import get_eval_config
@@ -190,6 +191,7 @@ class ExecuteTaggerInputs:
@temporalio.activity.defn
+@scoped_temporal()
async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]:
"""Execute LLM tagger to classify the target event."""
from django.utils import timezone
@@ -218,7 +220,7 @@ async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]
key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
if key.state != LLMProviderKey.State.OK:
raise ApplicationError(
- f"Your API key is {key.state}. Please fix or replace it.",
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
{"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
non_retryable=True,
)
diff --git a/products/ai_observability/backend/llm/providers/_diagnostics.py b/products/ai_observability/backend/llm/providers/_diagnostics.py
new file mode 100644
index 000000000000..af5bb5efd987
--- /dev/null
+++ b/products/ai_observability/backend/llm/providers/_diagnostics.py
@@ -0,0 +1,29 @@
+import httpx
+import posthoganalytics
+
+# Mirrors openai._base_client.DEFAULT_CONNECTION_LIMITS / anthropic._base_client.DEFAULT_CONNECTION_LIMITS.
+# Inlined rather than imported because both SDKs expose these via private `_base_client` modules.
+_PROVIDER_DEFAULT_LIMITS = httpx.Limits(max_connections=1000, max_keepalive_connections=100, keepalive_expiry=5.0)
+
+
+def _tag_response(response: httpx.Response) -> None:
+ try:
+ posthoganalytics.tag("provider.last_status", response.status_code)
+ request_id = (
+ response.headers.get("x-request-id")
+ or response.headers.get("anthropic-request-id")
+ or response.headers.get("openai-request-id")
+ )
+ if request_id:
+ posthoganalytics.tag("provider.last_request_id", request_id)
+ except Exception:
+ pass # instrumentation must never break the call
+
+
+def tagged_http_client(timeout: float | None = None) -> httpx.Client:
+ return httpx.Client(
+ event_hooks={"response": [_tag_response]},
+ limits=_PROVIDER_DEFAULT_LIMITS,
+ follow_redirects=True,
+ timeout=timeout if timeout is not None else httpx.Timeout(connect=5.0, read=600, write=600, pool=600),
+ )
diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.py
index c4667bd08007..ab9e108400cd 100644
--- a/products/ai_observability/backend/llm/providers/anthropic.py
+++ b/products/ai_observability/backend/llm/providers/anthropic.py
@@ -101,14 +101,24 @@ class AnthropicAdapter:
"""Non-streaming completion with optional structured output."""
effective_api_key = api_key or self._get_default_api_key()
+ from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+
posthog_client = posthoganalytics.default_client
client: Any
+ http_client = tagged_http_client(timeout=AnthropicConfig.TIMEOUT)
if analytics.capture and posthog_client:
client = Anthropic(
- api_key=effective_api_key, posthog_client=posthog_client, timeout=AnthropicConfig.TIMEOUT
+ api_key=effective_api_key,
+ posthog_client=posthog_client,
+ timeout=AnthropicConfig.TIMEOUT,
+ http_client=http_client,
)
else:
- client = anthropic.Anthropic(api_key=effective_api_key, timeout=AnthropicConfig.TIMEOUT)
+ client = anthropic.Anthropic(
+ api_key=effective_api_key,
+ timeout=AnthropicConfig.TIMEOUT,
+ http_client=http_client,
+ )
messages: Any = request.messages
system_prompt = request.system or ""
@@ -180,14 +190,24 @@ class AnthropicAdapter:
effective_api_key = api_key or self._get_default_api_key()
model_id = request.model
+ from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+
posthog_client = posthoganalytics.default_client
client: Any
+ http_client = tagged_http_client(timeout=AnthropicConfig.TIMEOUT)
if analytics.capture and posthog_client:
client = Anthropic(
- api_key=effective_api_key, posthog_client=posthog_client, timeout=AnthropicConfig.TIMEOUT
+ api_key=effective_api_key,
+ posthog_client=posthog_client,
+ timeout=AnthropicConfig.TIMEOUT,
+ http_client=http_client,
)
else:
- client = anthropic.Anthropic(api_key=effective_api_key, timeout=AnthropicConfig.TIMEOUT)
+ client = anthropic.Anthropic(
+ api_key=effective_api_key,
+ timeout=AnthropicConfig.TIMEOUT,
+ http_client=http_client,
+ )
reasoning_on = model_id in AnthropicConfig.SUPPORTED_MODELS_WITH_THINKING and request.thinking
diff --git a/products/ai_observability/backend/llm/providers/azure_openai.py b/products/ai_observability/backend/llm/providers/azure_openai.py
index e31a03f3b75a..9715850687c5 100644
--- a/products/ai_observability/backend/llm/providers/azure_openai.py
+++ b/products/ai_observability/backend/llm/providers/azure_openai.py
@@ -140,7 +140,10 @@ class AzureOpenAIAdapter(OpenAIAdapter):
analytics: AnalyticsContext,
) -> Any:
"""Create an AzureOpenAI client. Ignores base_url — uses azure_endpoint instead."""
+ from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+
posthog_client = posthoganalytics.default_client
+ http_client = tagged_http_client(timeout=OpenAIConfig.TIMEOUT)
if analytics.capture and posthog_client:
return WrappedAzureOpenAI(
posthog_client=posthog_client,
@@ -148,12 +151,14 @@ class AzureOpenAIAdapter(OpenAIAdapter):
azure_endpoint=self.azure_endpoint,
api_version=self.api_version,
timeout=OpenAIConfig.TIMEOUT,
+ http_client=http_client,
)
return openai.AzureOpenAI(
api_key=api_key,
azure_endpoint=self.azure_endpoint,
api_version=self.api_version,
timeout=OpenAIConfig.TIMEOUT,
+ http_client=http_client,
)
@staticmethod
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index 7008ff580989..abf387973049 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -104,8 +104,11 @@ class OpenAIAdapter:
analytics: AnalyticsContext,
) -> Any:
"""Create an OpenAI client. Override in subclasses for different client types (e.g. AzureOpenAI)."""
+ from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+
default_headers = self._get_default_headers()
posthog_client = posthoganalytics.default_client
+ http_client = tagged_http_client(timeout=OpenAIConfig.TIMEOUT)
if analytics.capture and posthog_client:
return OpenAI(
api_key=api_key,
@@ -113,12 +116,14 @@ class OpenAIAdapter:
base_url=base_url,
timeout=OpenAIConfig.TIMEOUT,
default_headers=default_headers or None,
+ http_client=http_client,
)
return openai.OpenAI(
api_key=api_key,
base_url=base_url,
timeout=OpenAIConfig.TIMEOUT,
default_headers=default_headers or None,
+ http_client=http_client,
)
def complete(
diff --git a/products/ai_observability/backend/llm/providers/test/test_diagnostics.py b/products/ai_observability/backend/llm/providers/test/test_diagnostics.py
new file mode 100644
index 000000000000..163b35fbe734
--- /dev/null
+++ b/products/ai_observability/backend/llm/providers/test/test_diagnostics.py
@@ -0,0 +1,153 @@
+import pytest
+
+import httpx
+import openai
+import anthropic
+import posthoganalytics
+
+from products.ai_observability.backend.llm.providers._diagnostics import _tag_response, tagged_http_client
+
+
+def _make_response(status: int = 200, headers: dict | None = None) -> httpx.Response:
+ return httpx.Response(
+ status_code=status,
+ headers=headers or {},
+ request=httpx.Request("GET", "https://example.com"),
+ )
+
+
+class TestTagResponse:
+ def test_tags_status_and_x_request_id(self):
+ with posthoganalytics.new_context():
+ _tag_response(_make_response(200, {"x-request-id": "req_abc"}))
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 200
+ assert tags["provider.last_request_id"] == "req_abc"
+
+ def test_falls_back_to_anthropic_request_id_header(self):
+ with posthoganalytics.new_context():
+ _tag_response(_make_response(429, {"anthropic-request-id": "req_ant"}))
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 429
+ assert tags["provider.last_request_id"] == "req_ant"
+
+ def test_falls_back_to_openai_request_id_header(self):
+ with posthoganalytics.new_context():
+ _tag_response(_make_response(403, {"openai-request-id": "req_oai"}))
+ assert posthoganalytics.get_tags()["provider.last_request_id"] == "req_oai"
+
+ def test_status_tagged_even_when_request_id_missing(self):
+ with posthoganalytics.new_context():
+ _tag_response(_make_response(500))
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 500
+ assert "provider.last_request_id" not in tags
+
+ def test_does_not_raise_when_called_outside_any_context(self):
+ # The Temporal-side activity wrappers create the context; if a hook
+ # somehow fires before that scope is open, we must not crash the request.
+ _tag_response(_make_response(200, {"x-request-id": "req_outside"}))
+
+ def test_does_not_leak_tags_outside_the_context(self):
+ # Belt-and-braces: contextvar isolation should already give us this, but
+ # this test pins the invariant so a future change to the helper that
+ # accidentally writes to global state fails loudly.
+ with posthoganalytics.new_context():
+ _tag_response(_make_response(200, {"x-request-id": "req_inside"}))
+ assert "provider.last_status" not in posthoganalytics.get_tags()
+ assert "provider.last_request_id" not in posthoganalytics.get_tags()
+
+
+class TestSDKIntegration:
+ """Verify the hook fires when the SDK actually drives the http_client.
+
+ Guards against future regressions where `http_client=` is dropped or routed
+ to a constructor that ignores it — the unit tests above would still pass.
+ """
+
+ @staticmethod
+ def _swap_mock_transport(client: httpx.Client, handler) -> None:
+ client._transport = httpx.MockTransport(handler)
+
+ def test_openai_sdk_invokes_hook(self):
+ http_client = tagged_http_client()
+ self._swap_mock_transport(
+ http_client,
+ lambda req: httpx.Response(
+ 200,
+ headers={"x-request-id": "req_openai_test"},
+ json={
+ "id": "chatcmpl-x",
+ "object": "chat.completion",
+ "created": 0,
+ "model": "gpt-test",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ ),
+ )
+ client = openai.OpenAI(api_key="sk-test", http_client=http_client)
+
+ with posthoganalytics.new_context():
+ client.chat.completions.create(model="gpt-test", messages=[{"role": "user", "content": "hi"}])
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 200
+ assert tags["provider.last_request_id"] == "req_openai_test"
+
+ def test_anthropic_sdk_invokes_hook(self):
+ http_client = tagged_http_client()
+ self._swap_mock_transport(
+ http_client,
+ lambda req: httpx.Response(
+ 200,
+ headers={"anthropic-request-id": "req_anthropic_test"},
+ json={
+ "id": "msg_x",
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "hi"}],
+ "model": "claude-test",
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ },
+ ),
+ )
+ client = anthropic.Anthropic(api_key="sk-test", http_client=http_client)
+
+ with posthoganalytics.new_context():
+ client.messages.create(
+ model="claude-test",
+ max_tokens=4,
+ messages=[{"role": "user", "content": "hi"}],
+ )
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 200
+ assert tags["provider.last_request_id"] == "req_anthropic_test"
+
+ def test_hook_does_not_break_request_on_provider_error(self):
+ # 4xx/5xx responses should still tag and not interfere with the SDK's
+ # own exception-raising path.
+ http_client = tagged_http_client()
+ self._swap_mock_transport(
+ http_client,
+ lambda req: httpx.Response(
+ 403,
+ headers={"x-request-id": "req_perm_denied"},
+ json={"error": {"code": "model_not_found", "message": "no access", "type": "invalid_request_error"}},
+ ),
+ )
+ client = openai.OpenAI(api_key="sk-test", http_client=http_client)
+
+ with posthoganalytics.new_context():
+ with pytest.raises(openai.PermissionDeniedError):
+ client.chat.completions.create(model="gpt-test", messages=[{"role": "user", "content": "hi"}])
+ tags = posthoganalytics.get_tags()
+ assert tags["provider.last_status"] == 403
+ assert tags["provider.last_request_id"] == "req_perm_denied"