: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): stop promising AI analysis on failed insights (#102289)
posthog[bot]1fcdd1f4c3e8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 296d6b5c85fc..90c4d8d97603 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9045,37 +9045,37 @@ snapshots:scenes-app-inbox-usagewidget--within-free-tier--light:hash: v1.k794b7964.85e2806575ce497e93a6c3dc95a39e6093f85422566cf852ea3d518569d29fc8.M8JloRqQpx2F1SkNFosfCxdACXJGX7FCxiv4421FROUscenes-app-insights-error-empty-states--empty--dark:- hash: v1.k794b7964.76b9de5735e998cd0643b9122af225ede95128f8d1087f438a8f13179a2cd314.j-ZaK3wWdoYedOoS0uqock8iOi4qHvyFl7W8j59NzPM+ hash: v1.k794b7964.ecb3db61cbdf2626fe76efc91c596d577bb4a290397a1f70fe67ab630fec601e.0G6XKBCX4pueOZEuUQsKvuhddVomaRRxOwLcSZt98T4scenes-app-insights-error-empty-states--empty--light:- hash: v1.k794b7964.43e8dc4bf97bb67ddaf60c572621f44670e53ae5e49adc85129ce56fe34112c2.sbomFpq1C6A2uPO2QNzFMa2oPgeAiU2Y6lNYz6qH_dc+ hash: v1.k794b7964.46a530c35e4a312654bd4e246e2957bceb9b53155b0373f583878c3050aa5266.pgKOAeSP4XI1Mk--AMqqA3ZeqFqP2dSpOd4jqagUOZEscenes-app-insights-error-empty-states--estimated-query-execution-time-too-long--dark:- hash: v1.k794b7964.fdde648da67a1ad03bef921fa62aff639acba275cb908e964ef214ea9e600d17.b0uYWTxVHoeGSR0U85AkoZdiNrc3zm8D4KaGyPT1H0g+ hash: v1.k794b7964.de439bb72e7fe5c45d9e5496d3b1746be4f4c9bb61bdcbf6b8013a27bb9a821f.VG1-NcicMV6mbV6GcKwlxpIE_1ZRaXn0FCqWruNqVr4scenes-app-insights-error-empty-states--estimated-query-execution-time-too-long--light:- hash: v1.k794b7964.666b12cd5ea2009ce3ea7269cd44cebd467b48ef272c2863f4fb78c74dd55d51.GDCwHpSZ6n5sIduVSyu002ujA_IAa6rp53i5w9nqk0Q+ hash: v1.k794b7964.096048d09a3eb961e9a8eb0a10aea2fa0d1ea51e375d38929de92a1348897fca.DFlyApG8inOeBoH8Q1hlyLJOhFLF029W1XlDURgRSrkscenes-app-insights-error-empty-states--funnel-single-step--dark:- hash: v1.k794b7964.95191b5eabf851e9190e78385e9b9c66305ef02e0239996a2505c12642a8cfe7.AzXYpom0Oilotqx9JOMUfUrK5VA4GaPcLHki2FkLGxw+ hash: v1.k794b7964.4b434a83047b9d303f76b1439f9b3a7b397aef561eed7e70873d54c2ee1c7e79.xQdyc0fgel2MgvkZo8jGQy4dAAvF0B6LHFYONMLFdI0scenes-app-insights-error-empty-states--funnel-single-step--light:- hash: v1.k794b7964.66bd00443e2e711874ed527bf57144f29725e97fe6485bd851a5a08fc1312baa.tlLUxnCoHj_VOErbA4ZPNkryCh306EmzhqWZkD8heAU+ hash: v1.k794b7964.626d7b24f478d96503b5bcc6216687d4298eaf0fe26aad7c19534a8485d7eee0.dzDHV0PyHfmpesJwqNCSFPdOb5kmNEuSV95PDYgJYecscenes-app-insights-error-empty-states--long-loading--dark:hash: v1.k794b7964.7e56525084d4787f75387ff2977d2c5871949141847d8aeaabe3f0c031dea5d1.xbYPGGVGgGHRAiaBBV8qoKBbczjZzTiE4hq9rW_ENgAscenes-app-insights-error-empty-states--long-loading--light:hash: v1.k794b7964.c17cf8b6b9ca9b3fa5cd570116c12705ec424367a8cf0cbe3934f7057a64bad6.xV9MB_rar116TwlG94C5F8W9YaSMd7NPI_AOO1OD9Icscenes-app-insights-error-empty-states--memory-limit-exceeded--dark:- hash: v1.k794b7964.2e48c122e036581194c9b2d7d1e9512af8193b1f72a74837cf5f12ba82b1fd72.9cdSq276OLtEWO5BwAxPIeX9y1JUV_x3gKBDf1DxZ80+ hash: v1.k794b7964.5d34330ba03d319f40a7e4e2e7cdb32fc8984e70951970f39a9ef70da6a70a97.SFBxyrukVvHwxMG4qO-R6CcAs9Mk1Td1fmLShKg15bkscenes-app-insights-error-empty-states--memory-limit-exceeded--light:- hash: v1.k794b7964.75ab2e919b3f7c36ea5cc85e3def80af2d1a130c359303da7a6350ffb08eca31.aQkEQ2HXsHZl7vz-D5BJxN5gMtRSX9RhzppllBsBZ2w+ hash: v1.k794b7964.f7fa16433b8652a53749cc634402df53e839e1f976cb675feef5cc94dee7c991.RnptYc38dpNrpnD38H_OzH8GL--z_2beHy11b9chiAcscenes-app-insights-error-empty-states--query-server-error--dark:- hash: v1.k794b7964.3005e0852a46a87ff251d145e22896b53f4bdd198e13e80ea8976eab02e34a16.l95y2LouxfDErePKQrTqH9A6exoO8zAfDKZ_POxOsoY+ hash: v1.k794b7964.8e86d1d4ab6af6159804e2801298842f1d086cbbb796c91fb60de816ab1abf5f.H93T__KkhRkfdLXG-mls00Kg7VOvi1uPJRzKchhICcoscenes-app-insights-error-empty-states--query-server-error--light:- hash: v1.k794b7964.ff89adcdbb0a5a832b14c2d574ed78dfbc195fb2bc2aaa4ed7c3f1636b36974e.ejXhasY1o2oPJ35r3ndql95zA9f88G-l5XSr7ejlMQM+ hash: v1.k794b7964.d8a09489dec3ccafe72938195eab9d2205c4f94c1d3d2921b37b4019bb2a10c3.h_DDpFNJx1Si9ffnyxJi-NhpWbSWzRFPekIqDSz71Iwscenes-app-insights-error-empty-states--server-error--dark:- hash: v1.k794b7964.09dc5604dc08ef589a43b504f4aad31cda03648a9e27c579e6c763cb446f6833.8_m3YxsizkrlwUHm7vZcquY8S-bnfmJuWDt9oiJUQTM+ hash: v1.k794b7964.8e86d1d4ab6af6159804e2801298842f1d086cbbb796c91fb60de816ab1abf5f.J7QYlsp_PAgkdRCMRB8buDteS7Gdpd4_tVO1BjQ_q8Uscenes-app-insights-error-empty-states--server-error--light:- hash: v1.k794b7964.67b3c028f98c71f3eb47d7e73447fbcb74a9e984ccf743ff53e463c8cf7a231c.RIXyy_KJP-pL-IW6sDS96WmPLCXwkchITd5ZTxjt7OE+ hash: v1.k794b7964.d8a09489dec3ccafe72938195eab9d2205c4f94c1d3d2921b37b4019bb2a10c3.tUHjsrFGt5D8TGMnQm1yjO8zFex-m83mZFRfNh8Hmhsscenes-app-insights-error-empty-states--validation-error--dark:- hash: v1.k794b7964.96f7a06307278330f327a5f2681c8151c8db64c5237d805d57a336d29dd83407.SgzGhQipeeQzM_7BmUHeTX2J0iq-wQl6zfd7CsTqpLI+ hash: v1.k794b7964.e9e73d44cdd981384511b3eeb25b0501678e0ab5d3884045181b6e3bc30975d9.RYaJRE9xA1zCvRiEmXzXYgSRPLyfnDjGZZ0iHrq4AYEscenes-app-insights-error-empty-states--validation-error--light:- hash: v1.k794b7964.30a50838e3fb15d9abf86197d074efed4fe0acc540be4ee3adf7a8194c4e5a7b.j4SWfv-lyqqnzhuC1zMkUVkisAelL9bSR4FBAmpD4_o+ hash: v1.k794b7964.5f92aa77178dd82ef8ae80db20e0f6643c1c93f1de596c801c11fb1909c59ab3.D2dDgNdqWwGxIaZRGTpyomI_-x1P8uTxNp6tkV32Fskscenes-app-insights-insight-quick-start--default--dark:hash: v1.k794b7964.9c2221e83fa5d09056672573226c948c5b9cd30716e6eb5e09d1e4ea3e94e336.WkGH5TXIN9Ysp3dVcJiXuGCjwdmC2Zquw_iUGoyj0jcscenes-app-insights-insight-quick-start--default--light:@@ -9085,9 +9085,9 @@ snapshots:scenes-app-insights-loading-messages--loading-messages--light:hash: v1.k794b7964.8127887a8cefedcd7ed93385885d6847022c7fa290f01ba60c42deb1216aa9b8.7DnuefE-HifUz5vzz32GzJAmV6eG8Or-yMF3OpaDuw8scenes-app-insights-mcp-missing-capability--mcp-missing-capability--dark:- hash: v1.k794b7964.0437dd655c7b78ec6e051f8a966a3db0aacaa698bbd575887696f03b1d277fc6.xBIh6OnGCQTM0zftdVNaO6ig0h-4oLpd3bIDgixmAzw+ hash: v1.k794b7964.dfd3cfa4c22429f905144ad610de438cd4685b2f160970762ee53a0c57b51f7c.36ljh4-ECCoIoGsxSqYp-Bl_q4ndSo-sORGvmxkm75Ascenes-app-insights-mcp-missing-capability--mcp-missing-capability--light:- hash: v1.k794b7964.27c8a5311feed5b8811a92f4651a5437b1776718dd951ac103c986a320c912e7.zv4ZV2Lh4TbIBWDm-5xZh6P6s6R55ut_-jDmzNAt7b0+ hash: v1.k794b7964.1b1a18bc74d3513095cfeb8a172f426cbda4d1b9b5df5ba59479d8ceb2399535.1TyzFZmRmUYsqc9Q5dnyZQtCF7gppER5cdCkVWMsNdcscenes-app-insights-side-panel-actions--saved-data-visualization--dark:hash: v1.k794b7964.3911a695d4b7b073bd0bfbaa183acb078d81df968e2cfecd18f84bc1c181bb66.2Hh9UrgF9n3vN3ZVif3FKqyz4F9mFROKhyLIEflEvDYscenes-app-insights-side-panel-actions--saved-data-visualization--light:@@ -9097,9 +9097,9 @@ snapshots:scenes-app-insights-side-panel-actions--saved-hog-ql-data-table--light:hash: v1.k794b7964.5b4c6ba0ac07ba8ea0dc4d24a980821992ee75f62b2f885972e5d332394bed34.PnQhji05di1PUTIp8bvdzvWMfEmF0FfC_K5lAZiLAEEscenes-app-insights-side-panel-actions--saved-trends-insight--dark:- hash: v1.k794b7964.367281449c1d127133be3d10f1399ced5911fecf1fa0472b2b6c96f42cd59982.xtTNJEe-E_Cb8FGrcMmvhwGC6Xgt8-e0loICGBvSSvM+ hash: v1.k794b7964.ca6aa0fcb43fabbc163a118cf47e12896792ac27c8542bb890706af614585139.GPsdx7U3h4XJeGs6zR-vu0RoNJ5leYxmJzDNcnbXd2Qscenes-app-insights-side-panel-actions--saved-trends-insight--light:- hash: v1.k794b7964.ae457c62363ca756235e3c518a25b61bfb23e65af80fde2e4ea73b69ce7b961c.9HK-y0iUK_31LwjHHDLvkGrfLuB67g1LQxwIo34JD68+ hash: v1.k794b7964.9d8c30bf0435f2dfe5886e044189addac343e59d7b9313841638c9e20b5feb1c.bBKHprQ8HyoXQT8MqlC0Q2dtNUvr_np2UFJ-mMEYoJgscenes-app-insights-side-panel-actions--unsaved-insight--dark:hash: v1.k794b7964.27e7bb90a746914ab15ebdf82e5353bc54017d8d40c6c985acd836b3bfb068ae.ubmfp9aIuKwIOUk_KfFdd7bkRuv77pjb2nA13vH3fQoscenes-app-insights-side-panel-actions--unsaved-insight--light:diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.test.tsxindex 9bb4d3a0553d..a44310f490bf 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.test.tsx@@ -1,6 +1,6 @@import { InsightType } from '~/types'-import { shouldShowDashboardInsightRefreshHint } from './InsightVizDisplay'+import { hasResultRows, shouldShowAIAnalysisSection, shouldShowDashboardInsightRefreshHint } from './InsightVizDisplay'const ALL_INSIGHT_TYPES = Object.values(InsightType) as InsightType[]/** Insight types that use the dashboard refresh hint (excludes web analytics — separate UX). */@@ -85,4 +85,46 @@ describe('InsightVizDisplay', () => {])('shouldShowDashboardInsightRefreshHint: $name', ({ params, expected }) => {expect(shouldShowDashboardInsightRefreshHint(params)).toBe(expected)})++ const AI_SECTION_BASE = {+ editMode: false,+ embedded: false,+ inSharedMode: false,+ hasQuerySource: true,+ insightDataLoading: false,+ hasBlockingEmptyState: false,+ hasResults: true,+ }++ it.each([+ { name: 'query succeeded with results', params: {}, expected: true },+ { name: 'query failed or timed out', params: { hasBlockingEmptyState: true }, expected: false },+ { name: 'query came back without results', params: { hasResults: false }, expected: false },+ {+ name: 'query still in flight — keep the section up so it does not appear late',+ params: { insightDataLoading: true, hasBlockingEmptyState: true, hasResults: false },+ expected: true,+ },+ { name: 'editing the insight', params: { editMode: true }, expected: false },+ { name: 'embedded', params: { embedded: true }, expected: false },+ { name: 'shared externally', params: { inSharedMode: true }, expected: false },+ { name: 'not an insight query node', params: { hasQuerySource: false }, expected: false },+ ])('shouldShowAIAnalysisSection: $name', ({ params, expected }) => {+ expect(shouldShowAIAnalysisSection({ ...AI_SECTION_BASE, ...params })).toBe(expected)+ })++ it.each([+ { name: 'trends series came back', insightData: { result: [{ label: 'Pageview', count: 3 }] }, expected: true },+ { name: 'query succeeded with no rows', insightData: { result: [] }, expected: false },+ { name: 'query succeeded with no rows under results', insightData: { results: [] }, expected: false },+ {+ name: 'all-zero series still counts as rows',+ insightData: { result: [{ data: [0, 0], count: 0 }] },+ expected: true,+ },+ { name: 'nothing came back', insightData: { result: null }, expected: false },+ { name: 'no payload at all', insightData: undefined, expected: false },+ ])('hasResultRows: $name', ({ insightData, expected }) => {+ expect(hasResultRows(insightData)).toBe(expected)+ })})diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex c2fbdb2a0836..fdd2882d12a3 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -101,6 +101,46 @@ function DashboardInsightRefreshHintOrLoading({return <InsightRefreshDataHint onRetry={onRetry} insightProps={insightProps} />}+function isNonEmptyResult(rows: unknown): boolean {+ return Array.isArray(rows) ? rows.length > 0 : rows != null+}++/** A settled query came back with rows. An empty success is `result: []`, so presence alone is not enough. */+export function hasResultRows(insightData: Record<string, any> | null | undefined): boolean {+ return isNonEmptyResult(insightData?.result) || isNonEmptyResult(insightData?.results)+}++/**+ * The "PostHog AI" section offers to explain the insight, so it only belongs next to results worth explaining.+ * It stays up while the query is in flight so it doesn't appear only once the chart draws. A query that+ * returned rows keeps it, even when the chart reads as empty, since that is what people ask PostHog AI about.+ */+export function shouldShowAIAnalysisSection({+ editMode,+ embedded,+ inSharedMode,+ hasQuerySource,+ insightDataLoading,+ hasBlockingEmptyState,+ hasResults,+}: {+ editMode?: boolean+ embedded?: boolean+ inSharedMode?: boolean+ hasQuerySource: boolean+ insightDataLoading: boolean+ hasBlockingEmptyState: boolean+ hasResults: boolean+}): boolean {+ if (editMode || embedded || inSharedMode || !hasQuerySource) {+ return false+ }+ if (insightDataLoading) {+ return true+ }+ return !hasBlockingEmptyState && hasResults+}+/** Dashboard tile: show refresh when merged `result` is still nullish (empty success is `[]`, not `null`). */export function shouldShowDashboardInsightRefreshHint({isInDashboardContext,@@ -476,22 +516,17 @@ export function InsightVizDisplay({}function renderAIAnalysisSection(): JSX.Element | null {- // Only show in view mode- if (editMode) {- return null- }-- // Don't show in embedded or shared mode- if (embedded || inSharedMode) {- return null- }-- // Only show for insight query nodes (use querySource which is the actual InsightQueryNode)- if (!querySource) {- return null- }-- return <InsightAIAnalysis />+ return shouldShowAIAnalysisSection({+ editMode,+ embedded,+ inSharedMode,+ hasQuerySource: !!querySource,+ insightDataLoading,+ hasBlockingEmptyState: !!BlockingEmptyState,+ hasResults: hasResultRows(insightData),+ }) ? (+ <InsightAIAnalysis />+ ) : null}const showComputationMetadata = !disableLastComputation || !!samplingFactordiff --git a/frontend/src/scenes/insights/InsightAIAnalysis.tsx b/frontend/src/scenes/insights/InsightAIAnalysis.tsxindex 5c7bcf1df2ed..a13a70079f0d 100644--- a/frontend/src/scenes/insights/InsightAIAnalysis.tsx+++ b/frontend/src/scenes/insights/InsightAIAnalysis.tsx@@ -20,10 +20,8 @@ export function InsightAIAnalysis(): JSX.Element | null {return (<div className="mt-4 mb-4">- <h2 className="font-semibold text-lg m-0 mb-2 flex items-center gap-2">AI analysis</h2>- <p className="text-muted mb-4">- Get AI-powered insights about your data, including trends, patterns, and actionable recommendations.- </p>+ <h2 className="font-semibold text-lg m-0 mb-2 flex items-center gap-2">PostHog AI</h2>+ <p className="text-muted mb-4">Open PostHog AI in the side panel and ask it what this insight shows.</p><div className="flex gap-2 flex-wrap"><AIConsentPopoverWrapper onApprove={() => openSidePanel(SidePanelTab.Max, '!Explain this insight')}><LemonButtondiff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 7370ec5c7486..4691a280c939 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -43,7 +43,6 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_paramfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.services.query import process_query_modelfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.sharing_publish_gate import blocked_access_for_user, is_publicly_sharedfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin@@ -175,10 +174,6 @@ from products.product_analytics.backend.presentation.insight_metadata import (InsightMetadataTimeoutError,generate_insight_metadata,)-from products.product_analytics.backend.presentation.insight_suggestions import (- get_insight_analysis,- get_insight_suggestions,-)from products.product_analytics.backend.presentation.insight_write_validation import validate_insight_writefrom common.hogvm.python.utils import HogVMException@@ -1773,8 +1768,8 @@ class InsightViewSet(parser_classes = (QuerySchemaParser,)def get_throttles(self):- """Apply LLM-specific throttles to AI analysis endpoints."""- if self.action in ["analyze", "suggestions", "generate_metadata"]:+ """Apply LLM-specific throttles to the AI metadata endpoint."""+ if self.action == "generate_metadata":return [AIObservabilitySummarizationBurstThrottle(),AIObservabilitySummarizationSustainedThrottle(),@@ -2238,94 +2233,6 @@ When set, the specified dashboard's filters and date range override will be applreturn response- @action(methods=["GET"], detail=True)- def analyze(self, request: Request, **kwargs) -> Response:- self._validate_ai_feature_access()-- insight = self.get_object()-- if not insight.query:- return Response({"result": ""})-- try:- query = schema.InsightVizNode.model_validate(insight.query)- except Exception:- return Response({"result": ""})-- result = None- try:- # We try to get cached result.- result_ctx = process_query_model(- self.team,- query,- execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,- user=request.user if request.user.is_authenticated else None,- analytics_props=get_request_analytics_properties(request),- )- if isinstance(result_ctx, BaseModel):- result = result_ctx.model_dump()- else:- result = result_ctx-- if result and result.get("results") is None and result.get("result") is None:- result = None- except Exception:- result = None-- analysis = get_insight_analysis(- query,- self.team,- result,- insight_name=insight.name,- insight_description=insight.description,- insight_id=insight.id,- )-- return Response({"result": analysis})-- @action(methods=["GET", "POST"], detail=True)- def suggestions(self, request: Request, **kwargs) -> Response:- self._validate_ai_feature_access()-- insight = self.get_object()-- if not insight.query:- return Response([])-- try:- query = schema.InsightVizNode.model_validate(insight.query)- except Exception:- return Response([])-- result = None- try:- # We try to get cached result.- result_ctx = process_query_model(- self.team,- query,- execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,- user=request.user if request.user.is_authenticated else None,- analytics_props=get_request_analytics_properties(request),- )- if isinstance(result_ctx, BaseModel):- result = result_ctx.model_dump()- else:- result = result_ctx-- if result and result.get("results") is None and result.get("result") is None:- result = None- except Exception:- result = None-- # Get context from POST body if provided- context = None- if request.method == "POST":- context = request.data.get("context")-- suggestions = get_insight_suggestions(query, self.team, result, context)-- return Response([s.model_dump() for s in suggestions])-@action(methods=["POST"], detail=False, required_scopes=["insight:write"])def generate_metadata(self, request: Request, **kwargs) -> Response:"""Generate an AI-suggested name and description for an insight based on its query configuration."""diff --git a/products/product_analytics/backend/presentation/insight_suggestions.py b/products/product_analytics/backend/presentation/insight_suggestions.pydeleted file mode 100644index e471393c40f3..000000000000--- a/products/product_analytics/backend/presentation/insight_suggestions.py+++ /dev/null@@ -1,311 +0,0 @@-import json-from typing import Any, Optional, Union--import structlog-from openai.types.chat import ChatCompletionMessageParam-from pydantic import BaseModel--from posthog.schema import (- ActionsNode,- EventsNode,- InsightVizNode,- IntervalType,- LifecycleQuery,- RetentionEntityKind,- RetentionPeriod,- RetentionQuery,- StickinessQuery,-)--from posthog.event_usage import groups-from posthog.llm.completions import hit_openai-from posthog.models import Team--from products.annotations.backend.facade.ai_context import build_annotations_block, resolve_query_date_range-from products.product_analytics.backend.facade.api import get_query_specific_instructions-from products.product_analytics.backend.presentation.ai_billing import billable_ai_properties--logger = structlog.get_logger(__name__)---class InsightSuggestion(BaseModel):- title: str- description: Optional[str] = None- targetQuery: InsightVizNode---def get_insight_suggestions(- query: InsightVizNode, team: Team, insight_result: Optional[dict[str, Any]] = None, context: Optional[str] = None-) -> list[InsightSuggestion]:- suggestions: list[InsightSuggestion] = []-- if isinstance(query.source, RetentionQuery):- suggestions.extend(get_retention_suggestions(query.source, query))-- if insight_result:- suggestions.extend(get_ai_suggestions(query, team, insight_result, context))-- return suggestions---def get_retention_suggestions(query: RetentionQuery, parent_query: InsightVizNode) -> list[InsightSuggestion]:- retention_filter = query.retentionFilter- returning_entity = retention_filter.returningEntity-- if not returning_entity:- return []-- series: list[Union[EventsNode, ActionsNode]] = []- entity_display_name = "event"-- # Handle Events- if returning_entity.type == "events" or returning_entity.kind == RetentionEntityKind.EVENTS_NODE:- event_name = returning_entity.id or returning_entity.name or "event"- entity_display_name = str(event_name)-- series = [- EventsNode(- kind="EventsNode",- event=str(event_name) if isinstance(event_name, str) else None,- name=returning_entity.name,- custom_name=returning_entity.custom_name,- properties=returning_entity.properties,- )- ]- # Handle Actions- elif returning_entity.type == "actions" or returning_entity.kind == RetentionEntityKind.ACTIONS_NODE:- action_id = int(returning_entity.id) if returning_entity.id else 0- entity_display_name = returning_entity.name or f"Action {action_id}"-- series = [- ActionsNode(- kind="ActionsNode",- id=action_id,- name=returning_entity.name,- custom_name=returning_entity.custom_name,- properties=returning_entity.properties,- )- ]- else:- return []-- # Auto-detect interval- retention_period = retention_filter.period or RetentionPeriod.DAY- interval = IntervalType.DAY- interval_description = "days per week"-- if retention_period == RetentionPeriod.MONTH:- interval = IntervalType.WEEK- interval_description = "weeks per month"- elif retention_period == RetentionPeriod.WEEK:- interval = IntervalType.DAY- interval_description = "days per week"- elif retention_period == RetentionPeriod.HOUR:- interval = IntervalType.HOUR- interval_description = "hours per day"-- # Stickiness Query- stickiness_query = StickinessQuery(- kind="StickinessQuery",- series=series,- interval=interval,- dateRange=query.dateRange,- properties=query.properties,- filterTestAccounts=query.filterTestAccounts,- stickinessFilter={},- )-- stickiness_target = InsightVizNode(- kind="InsightVizNode",- source=stickiness_query,- )-- # Lifecycle Query- lifecycle_query = LifecycleQuery(- kind="LifecycleQuery",- series=series,- interval=interval,- dateRange=query.dateRange,- properties=query.properties,- filterTestAccounts=query.filterTestAccounts,- lifecycleFilter={},- )-- lifecycle_target = InsightVizNode(- kind="InsightVizNode",- source=lifecycle_query,- )-- return [- InsightSuggestion(- title=f"Stickiness of users who performed {entity_display_name}",- description=f"See how frequently retained users perform this event ({interval_description})",- targetQuery=stickiness_target,- ),- InsightSuggestion(- title=f"Lifecycle of users who perform {entity_display_name}",- description="See lifecycle of users who perform this event (new vs returning vs resurrecting vs dormant)",- targetQuery=lifecycle_target,- ),- ]---def summarize_insight_result(result: Any) -> Any:- if isinstance(result, list):- return [summarize_insight_result(item) for item in result]- if isinstance(result, dict):- new_result = {}- for k, v in result.items():- if k in ["persons_urls", "persons", "action"]:- continue- new_result[k] = summarize_insight_result(v)- return new_result- return result---def get_insight_analysis(- query: InsightVizNode,- team: Team,- insight_result: Optional[dict[str, Any]],- insight_name: Optional[str] = None,- insight_description: Optional[str] = None,- insight_id: Optional[int] = None,-) -> str:- """Generate an AI analysis of the insight, highlighting main points and actionable items."""- try:- # We strip out large data like persons/urls but keep the filter and results- result_summary = (- json.dumps(summarize_insight_result(insight_result), default=str)- if insight_result- else "No results available"- )-- specific_instructions = get_query_specific_instructions(query.source.kind)-- context_str = ""- if insight_name:- context_str += f"Insight Name: {insight_name}\n"- if insight_description:- context_str += f"Insight Description: {insight_description}\n"-- annotations_block = build_annotations_block(- team,- resolve_query_date_range(query, team),- insight_ids=[insight_id] if insight_id else None,- )-- prompt = (- "You are a senior product data analyst. "- "Your goal is to explain *what* is happening in this insight and *why* it matters. "- "\n\n"- f"Specific Analysis Context: {specific_instructions}\n"- f"{context_str}\n"- "Output Requirements:\n"- "1. **Headline**: Start with a single, high-impact sentence summarizing the most important finding.\n"- "2. **Evidence**: Provide 2-3 concise bullet points (-) supporting the headline. You MUST quantify changes (e.g., '+15%', '2x higher', 'dropped by 30%') using the data provided.\n"- "3. **Takeaway**: End with one specific recommendation or question for further investigation.\n"- "\n"- "Style Rules:\n"- "- Be direct. Remove fluff like 'The chart shows', 'We can observe', or 'Based on the data'.\n"- "- Focus on *changes* and *differences*.\n"- "- Use plain text only (no markdown formatting like bold/italics) as the output will be rendered as raw text.\n"- "\n"- f"{annotations_block}"- f"Query Configuration: {query.model_dump_json(exclude_none=True)}\n\n"- f"Results Summary: {result_summary}"- )-- messages: list[ChatCompletionMessageParam] = [- {- "role": "system",- "content": "You are a helpful data analyst that provides concise, actionable insights about PostHog analytics data.",- },- {"role": "user", "content": prompt},- ]-- completion = hit_openai(- messages,- f"team/{team.id}/analysis",- posthog_properties=billable_ai_properties(team.id, "insight-ai-analysis"),- posthog_groups=groups(),- )- return completion.content-- except Exception:- logger.exception("ai_analysis_failed")- return ""---def get_ai_suggestions(- query: InsightVizNode, team: Team, insight_result: dict[str, Any], context: Optional[str] = None-) -> list[InsightSuggestion]:- try:- context_section = ""- if context:- context_section = f"\n\nPrevious Analysis Context:\n{context}\n\nUse this context to generate more relevant and targeted suggestions.\n"-- prompt = (- "You are an expert data analyst using PostHog. "- "Given the following analysis configuration and its results, suggest 3 relevant follow-up insights to explore deeper. "- "The suggestions should help the user understand *why* the results are the way they are, or explore related metrics.\n\n"- "Important Rules:\n"- "1. **Schema Compliance**: You must return a valid `InsightVizNode` JSON. \n"- " - `TrendsQuery` does NOT have `breakdown` or `display` fields directly.\n"- " - Use `breakdownFilter` object for breakdowns (e.g., `breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' }`).\n"- " - Use `trendsFilter` object for display (e.g., `trendsFilter: { display: 'ActionsBar' }`). Do NOT include 'yAxisScaleType' or other extra fields unless necessary and schema-compliant.\n"- " - `StickinessQuery` uses `series` list (like Trends), NOT a single `event` field.\n"- "2. **No Hallucination**: Use ONLY event names and property names that appear in the input query. Do not invent new properties like 'user_segment'.\n"- "3. **Simple Scope**: Focus on changing the visualization type (e.g. Trends, Stickiness), time interval, or breaking down by common properties like '$browser', '$os', '$geoip_country_code' ONLY if you are sure they are relevant. Prefer simple transformations of the existing query.\n\n"- "Provide the response as a JSON array of objects with the following keys:\n"- "- title: A short, descriptive title for the suggestion.\n"- "- description: A brief explanation of why this is interesting.\n"- "- query_json: A valid PostHog InsightVizNode JSON object that represents the suggested query.\n\n"- f"Current Query: {query.model_dump_json(exclude_none=True)}\n\n"- f"Results Summary: {json.dumps(summarize_insight_result(insight_result), default=str)}..."- f"{context_section}"- )-- messages: list[ChatCompletionMessageParam] = [- {- "role": "system",- "content": "You are a helpful assistant that generates PostHog insights in JSON format. You only return valid JSON arrays.",- },- {"role": "user", "content": prompt},- ]-- completion = hit_openai(- messages,- f"team/{team.id}/suggestions",- posthog_properties=billable_ai_properties(team.id, "insight-ai-suggestions"),- posthog_groups=groups(),- )-- # Parse JSON from content- cleaned_content = completion.content.strip()- if cleaned_content.startswith("```json"):- cleaned_content = cleaned_content[7:]- if cleaned_content.startswith("```"):- cleaned_content = cleaned_content[3:]- if cleaned_content.endswith("```"):- cleaned_content = cleaned_content[:-3]-- suggestions_data = json.loads(cleaned_content)-- suggestions = []- for item in suggestions_data:- try:- target_query = InsightVizNode.model_validate(item["query_json"])- suggestions.append(- InsightSuggestion(- title=item["title"], description=item.get("description"), targetQuery=target_query- )- )- except Exception as e:- logger.warning("invalid_ai_suggestion", error=str(e), suggestion=item)- continue-- return suggestions-- except Exception:- logger.exception("ai_suggestions_failed")- return []diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex d1b2d7495934..92df69906165 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -9233,42 +9233,6 @@ export const InsightsActivityRetrieveFormat = {Json: 'json',} as const-export type InsightsAnalyzeRetrieveParams = {- format?: InsightsAnalyzeRetrieveFormat-}--export type InsightsAnalyzeRetrieveFormat =- (typeof InsightsAnalyzeRetrieveFormat)[keyof typeof InsightsAnalyzeRetrieveFormat]--export const InsightsAnalyzeRetrieveFormat = {- Csv: 'csv',- Json: 'json',-} as const--export type InsightsSuggestionsRetrieveParams = {- format?: InsightsSuggestionsRetrieveFormat-}--export type InsightsSuggestionsRetrieveFormat =- (typeof InsightsSuggestionsRetrieveFormat)[keyof typeof InsightsSuggestionsRetrieveFormat]--export const InsightsSuggestionsRetrieveFormat = {- Csv: 'csv',- Json: 'json',-} as const--export type InsightsSuggestionsCreateParams = {- format?: InsightsSuggestionsCreateFormat-}--export type InsightsSuggestionsCreateFormat =- (typeof InsightsSuggestionsCreateFormat)[keyof typeof InsightsSuggestionsCreateFormat]--export const InsightsSuggestionsCreateFormat = {- Csv: 'csv',- Json: 'json',-} as const-export type InsightsAllActivityRetrieveParams = {format?: InsightsAllActivityRetrieveFormat/**diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.tsindex 1e0aaa0f4766..e1a6fc98c68e 100644--- a/products/product_analytics/frontend/generated/api.ts+++ b/products/product_analytics/frontend/generated/api.ts@@ -29,7 +29,6 @@ import type {InsightViewedRequestApi,InsightsActivityRetrieveParams,InsightsAllActivityRetrieveParams,- InsightsAnalyzeRetrieveParams,InsightsBulkDeleteCreateParams,InsightsBulkRestoreCreateParams,InsightsBulkSetTestAccountFilterCreateParams,@@ -42,8 +41,6 @@ import type {InsightsMyLastViewedRetrieveParams,InsightsPartialUpdateParams,InsightsRetrieveParams,- InsightsSuggestionsCreateParams,- InsightsSuggestionsRetrieveParams,InsightsTrendingRetrieveParams,InsightsUpdateParams,InsightsViewedCreateParams,@@ -563,105 +560,6 @@ export const insightsActivityRetrieve = async (})}-export const getInsightsAnalyzeRetrieveUrl = (- projectId: string,- id: number,- params?: InsightsAnalyzeRetrieveParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/insights/${id}/analyze/?${stringifiedParams}`- : `/api/projects/${projectId}/insights/${id}/analyze/`-}--export const insightsAnalyzeRetrieve = async (- projectId: string,- id: number,- params?: InsightsAnalyzeRetrieveParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getInsightsAnalyzeRetrieveUrl(projectId, id, params), {- ...options,- method: 'GET',- })-}--export const getInsightsSuggestionsRetrieveUrl = (- projectId: string,- id: number,- params?: InsightsSuggestionsRetrieveParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/insights/${id}/suggestions/?${stringifiedParams}`- : `/api/projects/${projectId}/insights/${id}/suggestions/`-}--export const insightsSuggestionsRetrieve = async (- projectId: string,- id: number,- params?: InsightsSuggestionsRetrieveParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getInsightsSuggestionsRetrieveUrl(projectId, id, params), {- ...options,- method: 'GET',- })-}--export const getInsightsSuggestionsCreateUrl = (- projectId: string,- id: number,- params?: InsightsSuggestionsCreateParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/insights/${id}/suggestions/?${stringifiedParams}`- : `/api/projects/${projectId}/insights/${id}/suggestions/`-}--export const insightsSuggestionsCreate = async (- projectId: string,- id: number,- insightApi?: NonReadonly<InsightApi>,- params?: InsightsSuggestionsCreateParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getInsightsSuggestionsCreateUrl(projectId, id, params), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(insightApi),- })-}-export const getInsightsAllActivityRetrieveUrl = (projectId: string, params?: InsightsAllActivityRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.tsindex ba25e643de4e..79cef7bd0c80 100644--- a/products/product_analytics/frontend/generated/api.zod.ts+++ b/products/product_analytics/frontend/generated/api.zod.ts@@ -203,10 +203,6 @@ export const InsightsPartialUpdateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')-export const InsightsSuggestionsCreateBody = /* @__PURE__ */ zod- .record(zod.string(), zod.unknown())- .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')-/*** Soft-delete insights in bulk by ID. Mirrors the single-insight delete: sets deleted=True, soft-deletes the insights' dashboard tiles, and removes their linked alerts. Insights the requester cannot edit are skipped and reported in `skipped`. Reversible via the bulk_restore endpoint.*/diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yamlindex a6de872ba529..21ac9217516d 100644--- a/products/product_analytics/mcp/tools.yaml+++ b/products/product_analytics/mcp/tools.yaml@@ -302,9 +302,6 @@ tools:- detail.changes.*.after- detail.trigger- detail.type- insights-analyze-retrieve:- operation: insights_analyze_retrieve- enabled: falseinsights-bulk-delete-create:operation: insights_bulk_delete_createenabled: false@@ -367,12 +364,6 @@ tools:insights-my-last-viewed-retrieve:operation: insights_my_last_viewed_retrieveenabled: false- insights-suggestions-create:- operation: insights_suggestions_create- enabled: false- insights-suggestions-retrieve:- operation: insights_suggestions_retrieve- enabled: falseinsights-trending-retrieve:operation: insights_trending_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3fb6977fdd70..072ecfbcae57 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -104969,42 +104969,6 @@ export namespace Schemas {Json: 'json',} as const;- export type InsightsAnalyzeRetrieveParams = {- format?: InsightsAnalyzeRetrieveFormat;- };-- export type InsightsAnalyzeRetrieveFormat = typeof InsightsAnalyzeRetrieveFormat[keyof typeof InsightsAnalyzeRetrieveFormat];--- export const InsightsAnalyzeRetrieveFormat = {- Csv: 'csv',- Json: 'json',- } as const;-- export type InsightsSuggestionsRetrieveParams = {- format?: InsightsSuggestionsRetrieveFormat;- };-- export type InsightsSuggestionsRetrieveFormat = typeof InsightsSuggestionsRetrieveFormat[keyof typeof InsightsSuggestionsRetrieveFormat];--- export const InsightsSuggestionsRetrieveFormat = {- Csv: 'csv',- Json: 'json',- } as const;-- export type InsightsSuggestionsCreateParams = {- format?: InsightsSuggestionsCreateFormat;- };-- export type InsightsSuggestionsCreateFormat = typeof InsightsSuggestionsCreateFormat[keyof typeof InsightsSuggestionsCreateFormat];--- export const InsightsSuggestionsCreateFormat = {- Csv: 'csv',- Json: 'json',- } as const;-export type InsightsAllActivityRetrieveParams = {format?: InsightsAllActivityRetrieveFormat;/**