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(data-imports): stop reporting a missing LLM gateway as an enrichment bug (#102362)

Tom Owers39c40293049e
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index 15aedc77f57b..af375772b37c 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -53,6 +53,15 @@ def team_distinct_id(team_id: int) -> str:
return f"team-{team_id}"
+class GatewayNotConfiguredError(ValueError):
+ """No LLM gateway is configured, so the client could not be built and no call was made.
+
+ A `ValueError` so existing callers keep behaving as before, but a distinct type so a caller whose
+ LLM step is optional can tell an absent gateway, which is static and the same for every team,
+ apart from a gateway call that went out and failed and is worth reporting.
+ """
+
+
def get_llm_client(
product: Product = "django",
team_id: int | None = None,
@@ -113,7 +122,7 @@ def get_llm_client(
"""
resolved_api_key = api_key or settings.LLM_GATEWAY_API_KEY
if not settings.LLM_GATEWAY_URL or not resolved_api_key:
- raise ValueError("LLM_GATEWAY_URL and an API key must be configured")
+ raise GatewayNotConfiguredError("LLM_GATEWAY_URL and an API key must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
headers = dict(default_headers or {})
@@ -138,7 +147,7 @@ def get_async_llm_client(
attribution and how to attach extra per-call event properties.
"""
if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
- raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
+ raise GatewayNotConfiguredError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
headers = dict(default_headers or {})
@@ -182,7 +191,7 @@ def get_async_anthropic_gateway_client(
Bedrock instead of failing. Sent as the `x-posthog-use-bedrock-fallback` default header.
"""
if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
- raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
+ raise GatewayNotConfiguredError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
default_headers = _team_id_header(team_id) if team_id is not None else {}
if use_bedrock_fallback:
@@ -205,7 +214,7 @@ def get_anthropic_gateway_client(
) -> Anthropic:
"""Synchronous variant of :func:`get_async_anthropic_gateway_client`."""
if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
- raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
+ raise GatewayNotConfiguredError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
headers = dict(default_headers or {})
if team_id is not None:
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 62e29dd491d2..07f2c5d9fe40 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -8,6 +8,7 @@ from django.test import override_settings
from posthog.llm.gateway_client import (
AIGatewayConfig,
+ GatewayNotConfiguredError,
Product,
build_ai_gateway_anthropic_client,
build_anthropic_client,
@@ -37,7 +38,7 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_URL = ""
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
- with pytest.raises(ValueError, match="LLM_GATEWAY_URL and an API key must be configured"):
+ with pytest.raises(GatewayNotConfiguredError, match="LLM_GATEWAY_URL and an API key must be configured"):
get_llm_client(product="django", team_id=1)
@patch("posthog.llm.gateway_client.settings")
@@ -45,7 +46,7 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
mock_settings.LLM_GATEWAY_API_KEY = ""
- with pytest.raises(ValueError, match="LLM_GATEWAY_URL and an API key must be configured"):
+ with pytest.raises(GatewayNotConfiguredError, match="LLM_GATEWAY_URL and an API key must be configured"):
get_llm_client(product="django", team_id=1)
@patch("posthog.llm.gateway_client.settings")
@@ -138,7 +139,9 @@ class TestGetAsyncAnthropicGatewayClient:
mock_settings.LLM_GATEWAY_URL = ""
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
- with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):
+ with pytest.raises(
+ GatewayNotConfiguredError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"
+ ):
get_async_anthropic_gateway_client(product="signals", team_id=1)
@patch("posthog.llm.gateway_client.settings")
diff --git a/products/data_modeling/backend/logic/enrich_view_semantics.py b/products/data_modeling/backend/logic/enrich_view_semantics.py
index b920ccce0457..9771f00b4b4d 100644
--- a/products/data_modeling/backend/logic/enrich_view_semantics.py
+++ b/products/data_modeling/backend/logic/enrich_view_semantics.py
@@ -26,7 +26,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
-from posthog.llm.gateway_client import Product
+from posthog.llm.gateway_client import GatewayNotConfiguredError, Product
from posthog.llm.semantic_enrichment import (
DEFAULT_ENRICHMENT_MODEL,
ENRICHMENT_BATCH_BUDGET_SECONDS,
@@ -512,6 +512,12 @@ def _run_enrichment_batches(target: _EnrichmentTarget, plan: _AnnotationPlan, lo
model=DEFAULT_ENRICHMENT_MODEL,
max_output_tokens=bounded.max_output_tokens,
)
+ except GatewayNotConfiguredError:
+ # No gateway in this deployment, so the call never went out. Reported as failed like any
+ # other unfinished pass, which withholds the hash so a later trigger retries, but kept out
+ # of error tracking because it fails identically for every view until one is configured.
+ log.warning("view_enrichment.llm_gateway_not_configured")
+ return _BatchRun(ai_count=ai_count, unfinished=remaining, failed=True)
except Exception as e:
capture_exception(e)
log.error("view_enrichment.llm_failed", error=str(e), exc_info=True)
diff --git a/products/data_modeling/backend/tests/test_enrich_view_semantics.py b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
index 494eeffe18d4..4c5b89ef3b89 100644
--- a/products/data_modeling/backend/tests/test_enrich_view_semantics.py
+++ b/products/data_modeling/backend/tests/test_enrich_view_semantics.py
@@ -4,6 +4,8 @@ from typing import Any
import pytest
from unittest.mock import patch
+from django.test import override_settings
+
from parameterized import parameterized
from posthog.llm.semantic_enrichment import MAX_OUTPUT_TOKENS
@@ -238,6 +240,26 @@ class TestEnrichViewSemanticsSync:
sq.refresh_from_db()
assert not sq.semantic_enrichment_hash
+ def test_an_unconfigured_gateway_is_not_reported_as_a_failure(self):
+ # A deployment with no LLM gateway fails identically for every view, so it stays out of error
+ # tracking, while the hash stays unstored so a later trigger enriches once one is configured.
+ team = _team()
+ sq = _saved_query(team, columns=_columns("amount"))
+
+ with (
+ patch.object(enrich, "get_team_business_context", return_value=""),
+ patch.object(enrich, "_gather_lineage", return_value=[]),
+ patch.object(enrich, "_get_row_sample", return_value=[]),
+ patch.object(enrich, "capture_exception") as mock_capture,
+ override_settings(LLM_GATEWAY_URL="", LLM_GATEWAY_API_KEY="", AI_GATEWAY_URL="", AI_GATEWAY_API_KEY=""),
+ ):
+ result = enrich_view_semantics_sync(team.pk, str(sq.id))
+
+ mock_capture.assert_not_called()
+ assert result["status"] == "partial"
+ sq.refresh_from_db()
+ assert not sq.semantic_enrichment_hash
+
def test_the_bounded_ceiling_reaches_the_request(self):
"""Pins the hand-off on this surface: without it the `max_output_tokens=` argument can be
deleted here with the suite green, restoring the flat cap."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
index 0c9d855618d2..db5c11fd3c58 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/enrich_table_semantics.py
@@ -27,6 +27,7 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy
from posthog.exceptions_capture import capture_exception
+from posthog.llm.gateway_client import GatewayNotConfiguredError
from posthog.llm.semantic_enrichment import (
DEFAULT_ENRICHMENT_MODEL,
MAX_BUSINESS_CONTEXT_CHARS,
@@ -432,6 +433,25 @@ def enrich_table_semantics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str,
columns_needing_description=columns_needing_description,
business_context=business_context,
)
+ except GatewayNotConfiguredError:
+ # No gateway in this deployment, so the call never went out. It fails identically for every
+ # team until one is configured, which no retry and no exception report can change. The
+ # canonical descriptions above are already persisted, and the columns left undescribed carry
+ # no annotation, so a later sync asks for them.
+ log.warning("warehouse_enrichment.llm_gateway_not_configured", canonical=canonical_count)
+ emit_completed(
+ "partial",
+ canonical_annotations=canonical_count,
+ ai_annotations=0,
+ llm_called=False,
+ reason="llm_gateway_not_configured",
+ )
+ return {
+ "status": "partial",
+ "canonical_annotations": canonical_count,
+ "ai_annotations": 0,
+ "error": "llm_gateway_not_configured",
+ }
except Exception as e:
capture_exception(e)
log.error(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
index d2854c0423cc..ed42c502eb0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_enrich_table_semantics.py
@@ -5,6 +5,8 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
+
from temporalio.testing import ActivityEnvironment
from posthog.llm.semantic_enrichment import MAX_OUTPUT_TOKENS, TruncatedCompletionError
@@ -749,6 +751,36 @@ class TestEnrichTableSemanticsSync:
assert result["error"] == "llm_failed"
assert _annotations(team, table) == {}
+ def test_unconfigured_gateway_is_not_reported_as_a_failure(self, _mock_capture_enrichment_event):
+ # A deployment with no LLM gateway fails identically for every team and no retry changes that,
+ # so it belongs in the completion event, not in error tracking.
+ team = _team()
+ schema, table = _make_schema(
+ team,
+ columns=[
+ {"name": "amount", "data_type": "Int64", "is_nullable": False},
+ {"name": "status", "data_type": "String", "is_nullable": True},
+ ],
+ )
+ canonical = {"Charge": {"columns": {"amount": "charge amount in cents"}}}
+ with (
+ patch.object(enrich, "get_canonical_descriptions_for_source", return_value=canonical),
+ patch.object(enrich, "_get_business_context", return_value=""),
+ patch.object(enrich, "capture_exception") as mock_capture,
+ override_settings(LLM_GATEWAY_URL="", LLM_GATEWAY_API_KEY="", AI_GATEWAY_URL="", AI_GATEWAY_API_KEY=""),
+ ):
+ result = enrich_table_semantics_sync(team.pk, schema.id)
+
+ mock_capture.assert_not_called()
+ assert result["status"] == "partial"
+ assert result["error"] == "llm_gateway_not_configured"
+ # The canonical description needs no gateway, so it still lands; the other column stays
+ # unannotated and a later sync asks for it again.
+ assert set(_annotations(team, table)) == {"amount"}
+ events = {call.args[1]: call.args[2] for call in _mock_capture_enrichment_event.call_args_list}
+ assert enrich.EVENT_ERROR not in events
+ assert events[enrich.EVENT_COMPLETED]["reason"] == "llm_gateway_not_configured"
+
def test_emits_started_completed_and_llm_call_events(self, _mock_capture_enrichment_event):
team = _team()
schema, _table = _make_schema(