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.

5.1 KB
Raw Blame
from collections.abc import AsyncGenerator
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from uuid import UUID

from posthog.schema import (
    ArtifactMessage,
    AssistantEventType,
    AssistantMessage,
    HumanMessage,
    MaxBillingContext,
    VisualizationArtifactContent,
    VisualizationMessage,
)

from posthog.event_usage import EventSource
from posthog.models import Team, User

from products.posthog_ai.backend.models.assistant import Conversation

from ee.hogai.artifacts.utils import unwrap_visualization_artifact_content
from ee.hogai.chat_agent.insights_graph.graph import InsightsGraph
from ee.hogai.chat_agent.stream_processor import ChatAgentStreamProcessor
from ee.hogai.core.runner import BaseAgentRunner
from ee.hogai.utils.types import AssistantOutput, AssistantState, PartialAssistantState
from ee.hogai.utils.types.base import AssistantNodeName

if TYPE_CHECKING:
    from ee.hogai.utils.types.composed import MaxNodeName


VERBOSE_NODES: set["MaxNodeName"] = {
    AssistantNodeName.QUERY_EXECUTOR,
    AssistantNodeName.FUNNEL_GENERATOR,
    AssistantNodeName.RETENTION_GENERATOR,
    AssistantNodeName.SQL_GENERATOR,
    AssistantNodeName.TRENDS_GENERATOR,
    AssistantNodeName.ROOT,
    AssistantNodeName.ROOT_TOOLS,
}


class InsightsAssistant(BaseAgentRunner):
    _state: Optional[AssistantState]
    _initial_state: Optional[AssistantState | PartialAssistantState]

    def __init__(
        self,
        team: Team,
        conversation: Conversation,
        *,
        new_message: Optional[HumanMessage] = None,
        user: User,
        session_id: Optional[str] = None,
        contextual_tools: Optional[dict[str, Any]] = None,
        is_new_conversation: bool = False,
        trace_id: Optional[str | UUID] = None,
        billing_context: Optional[MaxBillingContext] = None,
        initial_state: Optional[AssistantState | PartialAssistantState] = None,
        is_agent_billable: bool = True,
        event_source: EventSource = EventSource.POSTHOG_AI,
    ):
        super().__init__(
            team,
            conversation,
            new_message=new_message,
            user=user,
            graph_class=InsightsGraph,
            state_type=AssistantState,
            partial_state_type=PartialAssistantState,
            session_id=session_id,
            contextual_tools=contextual_tools,
            is_new_conversation=is_new_conversation,
            trace_id=trace_id,
            billing_context=billing_context,
            initial_state=initial_state,
            is_agent_billable=is_agent_billable,
            event_source=event_source,
            stream_processor=ChatAgentStreamProcessor(
                team=team,
                user=user,
                verbose_nodes=VERBOSE_NODES,
                streaming_nodes=set(),
                state_type=AssistantState,
            ),
        )

    def get_initial_state(self) -> AssistantState:
        return AssistantState(messages=[])

    def get_resumed_state(self) -> PartialAssistantState:
        if not self._latest_message:
            return PartialAssistantState(messages=[])
        return PartialAssistantState(
            messages=[self._latest_message], graph_status="resumed", query_generation_retry_count=0
        )

    async def astream(
        self,
        stream_message_chunks: bool = True,
        stream_subgraphs: bool = True,
        stream_first_message: bool = False,
        stream_only_assistant_messages: bool = False,
    ) -> AsyncGenerator[AssistantOutput]:
        last_ai_message: AssistantMessage | None = None
        last_artifact_content: VisualizationArtifactContent | None = None

        # stream_first_message is always False for this mode
        async for stream_event in super().astream(
            stream_message_chunks, stream_subgraphs, False, stream_only_assistant_messages
        ):
            path, message = stream_event
            if isinstance(message, ArtifactMessage) and (
                last_artifact_content := unwrap_visualization_artifact_content(message)
            ):
                # for backwards compatibility with the MCP
                legacy_visualization_message = VisualizationMessage(
                    id=message.id,
                    answer=last_artifact_content.query,
                    plan=last_artifact_content.description,
                )
                path = cast(Literal[AssistantEventType.MESSAGE], path)
                yield (path, legacy_visualization_message)
            if isinstance(message, AssistantMessage):
                last_ai_message = message
            yield stream_event

        if not self._initial_state:
            return
        visualization_response = (
            last_artifact_content.model_dump_json(exclude_none=True) if last_artifact_content else None
        )
        await self._report_conversation_state(
            "standalone ai tool call",
            {
                "prompt": self._initial_state.root_tool_insight_plan,
                "output": last_ai_message,
                "response": visualization_response,
                "tool_name": "create_and_query_insight",
                "is_new_conversation": False,
            },
        )