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.

7.8 KB
Raw Blame
import json
from typing import Any

from posthog.event_usage import EventSource
from posthog.hogql_queries.apply_dashboard_filters import (
    apply_dashboard_filters_to_dict,
    apply_dashboard_variables_to_dict,
)
from posthog.models import Team, User
from posthog.sync import database_sync_to_async

from products.product_analytics.backend.facade.models import Insight

from ee.hogai.context.insight.query_executor import execute_and_format_query, internal_error_code
from ee.hogai.tool_errors import MaxToolError, MaxToolRetryableError
from ee.hogai.utils.helpers import build_insight_url
from ee.hogai.utils.prompt import format_prompt_string
from ee.hogai.utils.query import validate_assistant_query
from ee.hogai.utils.types.base import AnyAssistantGeneratedQuery, AnyPydanticModelQuery

from .prompts import INSIGHT_RESULT_TEMPLATE


class InsightContext:
    """
    Formatter class for insight context used across the assistant.

    Accepts insight data directly and provides methods to format schema or execute and format results.
    Supports optional dashboard filter/variable overrides before execution.

    `insight_id` is only the identifier shown to the model; `insight_short_id` is the one that resolves to a
    URL, so an ephemeral artifact passes the former and leaves the latter unset.
    """

    def __init__(
        self,
        team: Team,
        query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery,
        *,
        user: User,
        name: str | None = None,
        description: str | None = None,
        insight_id: str | None = None,
        insight_model_id: int | None = None,
        insight_short_id: str | None = None,
        # Optional dashboard filter handling
        dashboard_filters: dict | None = None,
        filters_override: dict | None = None,
        variables_override: dict | None = None,
        event_source: EventSource = EventSource.POSTHOG_AI,
        max_sql_result_chars: int | None = None,
        saved_query: dict[str, Any] | None = None,
    ) -> None:
        self.team = team
        self.user = user
        self.event_source = event_source
        self.max_sql_result_chars = max_sql_result_chars
        self.query = query
        self.name = name
        self.description = description
        self.insight_id = insight_id
        self.insight_model_id = insight_model_id
        self.insight_short_id = insight_short_id
        self.dashboard_filters = dashboard_filters
        self.filters_override = filters_override
        self.variables_override = variables_override
        self.saved_query = saved_query

    @property
    def insight_url(self) -> str | None:
        """Generate insight URL from insight_short_id if available."""
        if self.insight_short_id:
            return build_insight_url(self.insight_short_id)
        return None

    @classmethod
    def extract_query(cls, insight: Insight):
        """Extract and validate query from insight, handling InsightVizNode wrapper."""

        query = insight.query
        if isinstance(query, dict) and query.get("source"):
            query = query.get("source")
        if not query:
            return None
        try:
            return validate_assistant_query(query)
        except Exception:
            return None

    async def execute_and_format(
        self,
        prompt_template: str = INSIGHT_RESULT_TEMPLATE,
        return_exceptions: bool = False,
        truncate_results: bool = True,
        include_prompt_framing: bool = True,
    ) -> str:
        """Execute query and format results."""
        effective_query = await self._get_effective_query()
        query_schema = self._format_query_schema(effective_query)
        effective_query_schema = self._format_effective_query_schema(effective_query)

        try:
            results = await execute_and_format_query(
                self.team,
                effective_query,
                insight_id=self.insight_model_id,
                truncate_results=truncate_results,
                user=self.user,
                include_prompt_framing=include_prompt_framing,
                event_source=self.event_source,
                max_sql_result_chars=self.max_sql_result_chars,
            )
        except Exception as e:
            error_message = f"Error executing query: {str(e)}"
            if return_exceptions:
                results = error_message
            elif isinstance(e, MaxToolError):
                raise
            else:
                raise MaxToolRetryableError(
                    error_message, error_type="internal", error_code=internal_error_code(e.__cause__ or e)
                ) from e

        return format_prompt_string(
            prompt_template,
            insight_name=self.name or "Insight",
            insight_id=self.insight_id,
            insight_description=self.description,
            query_schema=query_schema,
            is_saved_query=self.saved_query is not None,
            effective_query_schema=effective_query_schema,
            results=results,
            insight_url=self.insight_url,
        )

    async def format_schema(self, prompt_template: str = INSIGHT_RESULT_TEMPLATE) -> str:
        """Format insight as schema-only (no execution)."""
        query_schema = self._format_query_schema(await self._get_effective_query())
        return format_prompt_string(
            prompt_template,
            insight_name=self.name,
            insight_id=self.insight_id,
            insight_description=self.description,
            query_schema=query_schema,
            is_saved_query=self.saved_query is not None,
            insight_url=self.insight_url,
        )

    def _format_query_schema(self, effective_query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery) -> str:
        if self.saved_query is not None:
            # query_patch edits the stored query, so show it with its wrapper instead of the unwrapped query.
            return json.dumps(self.saved_query, separators=(",", ":"))
        return effective_query.model_dump_json(exclude_none=True)

    def _format_effective_query_schema(
        self, effective_query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery
    ) -> str | None:
        """The query that produced the results, when dashboard filters or variables make it differ from the saved query."""
        if self.saved_query is None:
            return None
        try:
            saved_query = validate_assistant_query(self.saved_query.get("source") or self.saved_query)
        except Exception:
            saved_query = None
        if saved_query is not None and self._comparable(saved_query) == self._comparable(effective_query):
            return None
        return effective_query.model_dump_json(exclude_none=True)

    @staticmethod
    def _comparable(query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery) -> dict[str, Any]:
        # The frontend fills in schema defaults and a version that saved queries often omit.
        dumped = query.model_dump(mode="json", exclude_none=True, exclude_defaults=True)
        dumped.pop("version", None)
        return dumped

    async def _get_effective_query(self):
        """Apply dashboard filters/overrides if provided."""
        if not (self.dashboard_filters or self.filters_override or self.variables_override):
            return self.query

        query_dict = self.query.model_dump(mode="json")

        if self.dashboard_filters:
            query_dict = await database_sync_to_async(apply_dashboard_filters_to_dict)(
                query_dict, self.dashboard_filters, self.team
            )

        if self.filters_override:
            query_dict = await database_sync_to_async(apply_dashboard_filters_to_dict)(
                query_dict, self.filters_override, self.team
            )

        if self.variables_override:
            query_dict = apply_dashboard_variables_to_dict(query_dict, self.variables_override, self.team)

        return validate_assistant_query(query_dict)