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(insights): make AI insight metadata generation robust to slow or malformed LLM responses (#68494)

posthog[bot]87b4139b5215
diff --git a/posthog/llm/completions.py b/posthog/llm/completions.py
index 40fbe4de3184..8d8a9f62d034 100644
--- a/posthog/llm/completions.py
+++ b/posthog/llm/completions.py
@@ -17,10 +17,19 @@ def hit_openai(
user: str,
posthog_properties: Optional[dict[str, Any]] = None,
posthog_groups: Optional[dict[str, Any]] = None,
+ timeout: float | None = None,
+ response_format: dict[str, Any] | None = None,
) -> tuple[str, int, int]:
if not openai_client:
raise ValueError("OPENAI_API_KEY environment variable not set")
+ # Only forward optional params when set, so callers that don't need them keep the client defaults.
+ optional_params: dict[str, Any] = {}
+ if timeout is not None:
+ optional_params["timeout"] = timeout
+ if response_format is not None:
+ optional_params["response_format"] = response_format
+
result = openai_client.chat.completions.create( # type: ignore
model="gpt-4.1-mini",
temperature=0,
@@ -28,6 +37,7 @@ def hit_openai(
user=user, # The user ID is for tracking within OpenAI in case of overuse/abuse
posthog_properties=posthog_properties,
posthog_groups=posthog_groups,
+ **optional_params,
)
content: str = ""
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 224aba07a8be..8fa32770d2cb 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -134,7 +134,10 @@ from products.alerts.backend.models.alert import AlertConfiguration
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
-from products.product_analytics.backend.api.insight_metadata import generate_insight_metadata
+from products.product_analytics.backend.api.insight_metadata import (
+ InsightMetadataTimeoutError,
+ generate_insight_metadata,
+)
from products.product_analytics.backend.api.insight_suggestions import get_insight_analysis, get_insight_suggestions
from products.product_analytics.backend.api.insight_variable import map_stale_to_latest
from products.product_analytics.backend.models.insight import Insight, InsightViewed
@@ -2057,6 +2060,9 @@ When set, the specified dashboard's filters and date range override will be appl
try:
metadata = generate_insight_metadata(validated_query, self.team)
+ except InsightMetadataTimeoutError as e:
+ capture_exception(e)
+ raise APIException("Generating a name took too long. Please try again.")
except Exception as e:
capture_exception(e)
raise APIException("Failed to generate insight metadata. Please try again.")
diff --git a/products/product_analytics/backend/api/insight_metadata.py b/products/product_analytics/backend/api/insight_metadata.py
index 1dde47fbe44c..c4188b5e0442 100644
--- a/products/product_analytics/backend/api/insight_metadata.py
+++ b/products/product_analytics/backend/api/insight_metadata.py
@@ -1,6 +1,7 @@
import json
from typing import Any
+import openai
import structlog
from openai.types.chat import ChatCompletionMessageParam
from pydantic import BaseModel
@@ -27,8 +28,24 @@ class InsightMetadata(BaseModel):
description: str
+class InsightMetadataGenerationError(Exception):
+ """Base error for AI insight metadata generation failures."""
+
+
+class InsightMetadataTimeoutError(InsightMetadataGenerationError):
+ """The LLM call did not return within the allotted time."""
+
+
+class InsightMetadataParseError(InsightMetadataGenerationError):
+ """The LLM returned a response we could not parse into a name and description."""
+
+
logger = structlog.get_logger(__name__)
+# Keep the LLM call bounded so a slow OpenAI response fails fast instead of hanging the request.
+_LLM_TIMEOUT_SECONDS = 20.0
+_MAX_PARSE_ATTEMPTS = 2
+
_MATH_LABELS: dict[str, str] = {
"total": "total count",
@@ -462,57 +479,90 @@ def _generate_insight_viz_metadata(query: InsightVizNode, team: Team) -> Insight
return _request_metadata_from_llm(query_summary, type_guidance, team)
-def _request_metadata_from_llm(query_summary: str, type_guidance: str, team: Team) -> InsightMetadata:
+def _parse_metadata(content: str) -> InsightMetadata:
+ """Parse the LLM response into a name and description, tolerating minor sloppiness.
+
+ Raises InsightMetadataParseError if the response is not usable JSON with a name.
+ """
try:
- prompt = (
- "Name and describe this product analytics insight for a dashboard. "
- "Optimize for clarity and scanability — a teammate should instantly understand "
- "what this insight tracks at a glance.\n\n"
- f"{type_guidance}\n\n"
- "Rules for the NAME:\n"
- "- Title case (e.g. 'Pageviews, Pageleaves')\n"
- "- 3-12 words — use as many as needed to capture all series and breakdowns\n"
- "- Humanize event names: '$pageview' → 'Pageviews', 'user_signed_up' → 'Signups'\n"
- "- Include 'by <dimension>' only when a breakdown is present. Multiple breakdowns - join with 'and': 'by Browser and OS'\n"
- "- Drop filler words: 'count', 'total', 'events', 'data', 'trend'\n"
- "- If math is just total count, omit it — it's the default\n\n"
- "Rules for the DESCRIPTION:\n"
- "- One short sentence — what this insight measures\n"
- "- Plain language, no jargon\n\n"
- "Query:\n"
- f"{query_summary}\n\n"
- 'Return ONLY a JSON object: {"name": "...", "description": "..."}'
- )
+ parsed = json.loads(content.strip())
+ except (json.JSONDecodeError, TypeError) as e:
+ raise InsightMetadataParseError("LLM response was not valid JSON") from e
- messages: list[ChatCompletionMessageParam] = [
- {
- "role": "system",
- "content": (
- "You are a helpful assistant that generates insight names and descriptions. "
- "Return only a JSON object with 'name' and 'description' keys, nothing else."
- ),
- },
- {"role": "user", "content": prompt},
- ]
-
- content, _, _ = hit_openai(
- messages,
- f"team/{team.id}/generate-insight-metadata",
- posthog_properties=billable_ai_properties(team.id, "insight-ai-metadata-generation"),
- posthog_groups=groups(),
- )
+ if not isinstance(parsed, dict):
+ raise InsightMetadataParseError("LLM response was not a JSON object")
- parsed = json.loads(content.strip())
- name = parsed["name"].strip().strip('"').strip("'")
- description = parsed["description"].strip()
+ name = str(parsed.get("name") or "").strip().strip('"').strip("'")
+ description = str(parsed.get("description") or "").strip()
+
+ if not name:
+ raise InsightMetadataParseError("LLM response was missing a name")
- if len(name) > 100:
- name = name[:97] + "..."
- if len(description) > 200:
- description = description[:197] + "..."
+ if len(name) > 100:
+ name = name[:97] + "..."
+ if len(description) > 200:
+ description = description[:197] + "..."
- return InsightMetadata(name=name, description=description)
+ return InsightMetadata(name=name, description=description)
+
+
+def _request_metadata_from_llm(query_summary: str, type_guidance: str, team: Team) -> InsightMetadata:
+ prompt = (
+ "Name and describe this product analytics insight for a dashboard. "
+ "Optimize for clarity and scanability — a teammate should instantly understand "
+ "what this insight tracks at a glance.\n\n"
+ f"{type_guidance}\n\n"
+ "Rules for the NAME:\n"
+ "- Title case (e.g. 'Pageviews, Pageleaves')\n"
+ "- 3-12 words — use as many as needed to capture all series and breakdowns\n"
+ "- Humanize event names: '$pageview' → 'Pageviews', 'user_signed_up' → 'Signups'\n"
+ "- Include 'by <dimension>' only when a breakdown is present. Multiple breakdowns - join with 'and': 'by Browser and OS'\n"
+ "- Drop filler words: 'count', 'total', 'events', 'data', 'trend'\n"
+ "- If math is just total count, omit it — it's the default\n\n"
+ "Rules for the DESCRIPTION:\n"
+ "- One short sentence — what this insight measures\n"
+ "- Plain language, no jargon\n\n"
+ "Query:\n"
+ f"{query_summary}\n\n"
+ 'Return ONLY a JSON object: {"name": "...", "description": "..."}'
+ )
- except Exception:
- logger.exception("ai_metadata_generation_failed")
- raise
+ messages: list[ChatCompletionMessageParam] = [
+ {
+ "role": "system",
+ "content": (
+ "You are a helpful assistant that generates insight names and descriptions. "
+ "Return only a JSON object with 'name' and 'description' keys, nothing else."
+ ),
+ },
+ {"role": "user", "content": prompt},
+ ]
+
+ # JSON mode makes the output reliably parseable; the timeout stops a slow OpenAI call from
+ # hanging the request. On a parse failure we retry once before giving up.
+ last_parse_error: InsightMetadataParseError | None = None
+ for attempt in range(_MAX_PARSE_ATTEMPTS):
+ try:
+ content, _, _ = hit_openai(
+ messages,
+ f"team/{team.id}/generate-insight-metadata",
+ posthog_properties=billable_ai_properties(team.id, "insight-ai-metadata-generation"),
+ posthog_groups=groups(),
+ timeout=_LLM_TIMEOUT_SECONDS,
+ response_format={"type": "json_object"},
+ )
+ except openai.APITimeoutError as e:
+ logger.warning("ai_metadata_generation_timeout", team_id=team.id)
+ raise InsightMetadataTimeoutError("The AI service took too long to respond") from e
+ except Exception as e:
+ logger.exception("ai_metadata_generation_llm_error", team_id=team.id)
+ raise InsightMetadataGenerationError("The AI service failed to respond") from e
+
+ try:
+ return _parse_metadata(content)
+ except InsightMetadataParseError as e:
+ last_parse_error = e
+ logger.warning("ai_metadata_generation_parse_failed", team_id=team.id, attempt=attempt)
+
+ logger.error("ai_metadata_generation_parse_exhausted", team_id=team.id)
+ raise last_parse_error or InsightMetadataParseError("Could not parse the AI response")
diff --git a/products/product_analytics/backend/api/test/test_insight_metadata.py b/products/product_analytics/backend/api/test/test_insight_metadata.py
index 3493fad8542f..b921628964e0 100644
--- a/products/product_analytics/backend/api/test/test_insight_metadata.py
+++ b/products/product_analytics/backend/api/test/test_insight_metadata.py
@@ -1,6 +1,8 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+import httpx
+import openai
from parameterized import parameterized
from rest_framework import status
@@ -58,6 +60,43 @@ class TestGenerateInsightMetadata(APIBaseTest):
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert "Failed" in response.json()["detail"]
+ @patch(
+ MOCK_PATH,
+ side_effect=openai.APITimeoutError(request=httpx.Request("POST", "https://api.openai.com")),
+ )
+ def test_llm_timeout_returns_distinct_error(self, mock_openai):
+ response = self.client.post(self.url, {"query": _trends_query()}, format="json")
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ # Timeouts are surfaced distinctly from the generic parse/failure path so they can be told apart.
+ assert "too long" in response.json()["detail"]
+
+ @patch(MOCK_PATH, return_value=("not valid json at all", 10, 20))
+ def test_unparseable_response_retries_then_returns_500(self, mock_openai):
+ response = self.client.post(self.url, {"query": _trends_query()}, format="json")
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert "Failed" in response.json()["detail"]
+ assert mock_openai.call_count == 2
+
+ @patch(MOCK_PATH)
+ def test_missing_description_is_tolerated(self, mock_openai):
+ mock_openai.return_value = ('{"name": "Daily Pageviews"}', 10, 20)
+ response = self.client.post(self.url, {"query": _trends_query()}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["name"] == "Daily Pageviews"
+ assert response.json()["description"] == ""
+
+ @patch(MOCK_PATH)
+ def test_forwards_json_mode_and_timeout(self, mock_openai):
+ mock_openai.return_value = ('{"name": "Daily Pageviews", "description": "Tracks daily page views."}', 10, 20)
+ response = self.client.post(self.url, {"query": _trends_query()}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert mock_openai.call_args.kwargs["response_format"] == {"type": "json_object"}
+ assert mock_openai.call_args.kwargs["timeout"] is not None
+
def test_ai_not_approved_returns_403(self):
self.organization.is_ai_data_processing_approved = False
self.organization.save()