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(ai-observability): handle transient network errors in Gemini adapter (#75000)

posthog[bot]c46339187a77
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index ddaf71dd29b0..8c7eeb18af49 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -35,6 +35,7 @@ from products.ai_observability.backend.llm.errors import (
ContextWindowExceededError,
ModelNotFoundError,
ModelPermissionError,
+ ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
@@ -408,6 +409,13 @@ def call_llm_judge(
increment_errors("context_window_exceeded", provider=provider)
return _build_context_window_skip_result(allows_na, is_byok=is_byok, key_id=key_id)
+ except ProviderConnectionError:
+ # Transient transport failure (connection reset, read timeout). Retrying usually succeeds,
+ # so track it as a metric and re-raise for the retry policy — without the logger.exception
+ # that would clutter error tracking with a non-actionable issue.
+ increment_errors("connection_error", provider=provider)
+ raise
+
except Exception as e:
logger.exception(
"Unhandled error from LLM client",
diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.py
index 85eb08d9f705..8a06c62f89ae 100644
--- a/products/ai_observability/backend/llm/errors.py
+++ b/products/ai_observability/backend/llm/errors.py
@@ -30,6 +30,12 @@ class QuotaExceededError(LLMError):
"""Raised when API quota is exceeded"""
+class ProviderConnectionError(LLMError):
+ """Raised on a transient network/transport error talking to the provider — connection reset,
+ read timeout, DNS failure. Retryable: callers should retry rather than treat it as a hard error,
+ and should not log it as an exception since it's usually resolved on the next attempt."""
+
+
class ProviderMismatchError(LLMError):
"""Raised when request provider doesn't match provider key's provider"""
diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.py
index 49b69c3f63b0..42ee834db1fd 100644
--- a/products/ai_observability/backend/llm/providers/anthropic.py
+++ b/products/ai_observability/backend/llm/providers/anthropic.py
@@ -17,6 +17,7 @@ from pydantic import BaseModel
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ContextWindowExceededError,
+ ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
@@ -196,6 +197,10 @@ class AnthropicAdapter:
if _is_quota_or_billing_error(e):
raise QuotaExceededError(str(e)) from e
raise RateLimitError(str(e)) from e
+ except anthropic.APIConnectionError as e:
+ # Transient transport failure (connection reset, read timeout). Map to a quiet
+ # retryable error so the caller retries silently instead of spamming error tracking.
+ raise ProviderConnectionError(str(e)) from e
def stream(
self,
diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.py
index c42f710cb69b..31635684bf0c 100644
--- a/products/ai_observability/backend/llm/providers/gemini.py
+++ b/products/ai_observability/backend/llm/providers/gemini.py
@@ -8,6 +8,7 @@ from typing import Any
from django.conf import settings
+import httpx
import posthoganalytics
from google import genai
from google.genai.errors import APIError
@@ -19,6 +20,7 @@ from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ModelNotFoundError,
ModelPermissionError,
+ ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
@@ -152,6 +154,11 @@ class GeminiAdapter:
if status_code == 404 or "no longer available" in error_message or "not found" in error_message:
raise ModelNotFoundError(request.model)
raise
+ except httpx.TransportError as e:
+ # google-genai doesn't wrap httpx transport failures (connection reset, read timeout)
+ # in APIError, so without this they escape as an unmapped exception and spam error
+ # tracking. Map to a quiet retryable error so the caller retries silently.
+ raise ProviderConnectionError(str(e)) from e
def stream(
self,
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index 5a6b5624ab4a..15fcfb30b5ba 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -23,6 +23,7 @@ from products.ai_observability.backend.llm.errors import (
ContextWindowExceededError,
ModelNotFoundError,
ModelPermissionError,
+ ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
@@ -205,6 +206,10 @@ class OpenAIAdapter:
if error_code == "insufficient_quota":
raise QuotaExceededError(str(e))
raise RateLimitError(str(e))
+ except openai.APIConnectionError as e:
+ # Transient transport failure (connection reset, read timeout). Map to a quiet
+ # retryable error so the caller retries silently instead of spamming error tracking.
+ raise ProviderConnectionError(str(e)) from e
except openai.APIStatusError as e:
if isinstance(e, openai.BadRequestError) and is_context_window_error_message(str(e)):
raise ContextWindowExceededError(str(e)) from e
diff --git a/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py b/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
index 238211d10dca..05a327fa9646 100644
--- a/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
+++ b/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
@@ -1,6 +1,7 @@
import pytest
from unittest.mock import MagicMock, patch
+import httpx
from google.genai.errors import ClientError
from parameterized import parameterized
@@ -8,6 +9,7 @@ from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ModelNotFoundError,
ModelPermissionError,
+ ProviderConnectionError,
RateLimitError,
)
from products.ai_observability.backend.llm.providers.gemini import GeminiAdapter, GeminiConfig
@@ -61,3 +63,20 @@ class TestGeminiAdapterErrorMapping:
with patch("products.ai_observability.backend.llm.providers.gemini.genai.Client", return_value=mock_client):
with pytest.raises(expected):
adapter.complete(request, api_key="test-key", analytics=AnalyticsContext(capture=False))
+
+ def test_transport_error_is_mapped_to_provider_connection_error(self):
+ # google-genai leaks raw httpx transport errors (connection reset) rather than wrapping
+ # them in APIError, so they'd escape the mapping above without a dedicated branch.
+ request = CompletionRequest(
+ model="gemini-2.0-flash-lite",
+ system="s",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="gemini",
+ )
+ adapter = GeminiAdapter()
+ mock_client = MagicMock()
+ mock_client.models.generate_content.side_effect = httpx.ReadError("[Errno 104] Connection reset by peer")
+
+ with patch("products.ai_observability.backend.llm.providers.gemini.genai.Client", return_value=mock_client):
+ with pytest.raises(ProviderConnectionError):
+ adapter.complete(request, api_key="test-key", analytics=AnalyticsContext(capture=False))