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.

6.8 KB
Raw Blame
from typing import Any, Literal, Self, Union

from langchain_core.runnables import RunnableConfig
from pydantic import BaseModel, Field, ValidationError, create_model

from posthog.models import Team, User

from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit
from ee.hogai.context.context import AssistantContextManager
from ee.hogai.tool import MaxTool
from ee.hogai.tool_errors import MaxToolRetryableError
from ee.hogai.utils.types.base import AssistantState, NodePath

from .core import (
    ReadActionProperties,
    ReadActionSamplePropertyValues,
    ReadEntityProperties,
    ReadEntitySamplePropertyValues,
    ReadEventProperties,
    ReadEvents,
    ReadEventSamplePropertyValues,
    ReadTaxonomyToolArgs,
    execute_taxonomy_query,
)

READ_TAXONOMY_TOOL_DESCRIPTION = """
Use this tool to explore the user's taxonomy (i.e. data schema).
The user implements PostHog SDKs to collect events, properties, and property values. They are used by users to create insights with visualizations, SQL queries, watch session recordings, filter data, target particular users or groups by traits or behavior, etc.
Each event, action, and entity has its own data schema. You must verify that specific combinations exist before using it anywhere else.
Events or properties starting from "$" are system properties automatically captured by SDKs.
Do not rely on your training data or PostHog defaults for events or properties. Always use this tool to confirm what actually exists in the user's project before referencing any event, property, or property value.
When reading events, you can paginate using `limit` (1-500, default 500) and `offset` (default 0) on the ReadEvents query. If the response indicates more events are available, increment the offset to fetch subsequent pages.

# Query types

Use exact `kind` values and field names as shown below:
- kind: "events" — list available events. Optional: `limit` (1-500), `offset`.
- kind: "event_properties" — properties for an event. Required: `event_name`.
- kind: "event_property_values" — sample values for an event property. Required: `event_name`, `property_name`.
- kind: "entity_properties" — properties for an entity. Required: `entity` (one of "person", "session", or a group name).
- kind: "entity_property_values" — sample values for an entity property. Required: `entity`, `property_name`.
- kind: "action_properties" — properties for an action. Required: `action_id`.
- kind: "action_property_values" — sample values for an action property. Required: `action_id`, `property_name`.

# Examples of when to use the read_taxonomy tool

<example>
User: What event can I use to track revenue?
Assistant: I'm going to retrieve events and event properties to help you find the event you're looking for.
*Retrieves events*
Assistant: I've found a few matching events. I'm going to retrieve event properties to help you find the event you're looking for.
*Retrieves event properties for each event*
Assistant: I've found a few matching properties. I'm going to retrieve sample property values for each property to verify they can be used for revenue tracking.
*Retrieves sample property values for each event property*
Assistant: I've found matching combinations...

<reasoning>
The assistant used the read_taxonomy tool because:
1. The user is asking about **their custom data schema** in PostHog.
2. The assistant needs to find a specific combination of events, properties, and property values that can be used to track revenue.
</reasoning>
</example>

# Examples of when NOT to use the read_taxonomy tool

<example>
User: What system properties does PostHog capture?
Assistant: I'm going to search PostHog documentation to find the system properties that are automatically captured by SDKs.
*Begins searching PostHog documentation*

<reasoning>
The assistant did not use the read_taxonomy tool because it is an informational request. The user is simply asking for documentation search.
</reasoning>
</example>
""".strip()


class ReadTaxonomyTool(MaxTool):
    name: Literal["read_taxonomy"] = "read_taxonomy"
    description: str = READ_TAXONOMY_TOOL_DESCRIPTION
    context_prompt_template: str = (
        "Explores the user's events, actions, properties, and property values (i.e. taxonomy)."
    )

    def _run_impl(self, query: dict[str, Any]) -> tuple[str, Any]:
        # Langchain can't parse a dynamically created Pydantic model, so we need to additionally validate the query here.
        try:
            validated_query = ReadTaxonomyToolArgs(query=query).query
        except ValidationError as e:
            raise MaxToolRetryableError(str(e))

        toolkit = TaxonomyAgentToolkit(self._team, self._user)

        try:
            res = execute_taxonomy_query(validated_query, toolkit, self._team, self._user)
        except ValueError as e:
            raise MaxToolRetryableError(str(e))

        return res, None

    @classmethod
    async def create_tool_class(
        cls,
        *,
        team: Team,
        user: User,
        node_path: tuple[NodePath, ...] | None = None,
        state: AssistantState | None = None,
        config: RunnableConfig | None = None,
        context_manager: AssistantContextManager | None = None,
    ) -> Self:
        context_manager = AssistantContextManager(team, user, config)
        group_names = await context_manager.get_group_names()

        # Create Literal type with actual entity names
        EntityKind = Literal["person", "session", *group_names]  # type: ignore

        ReadEntityPropertiesWithGroups = create_model(
            "ReadEntityProperties",
            __base__=ReadEntityProperties,
            entity=(
                EntityKind,
                Field(description=ReadEntityProperties.model_fields["entity"].description),
            ),
        )

        ReadEntitySamplePropertyValuesWithGroups = create_model(
            "ReadEntitySamplePropertyValues",
            __base__=ReadEntitySamplePropertyValues,
            entity=(
                EntityKind,
                Field(description=ReadEntitySamplePropertyValues.model_fields["entity"].description),
            ),
        )

        ReadTaxonomyQueryWithGroups = Union[
            ReadEvents,
            ReadEventProperties,
            ReadEventSamplePropertyValues,
            ReadEntityPropertiesWithGroups,
            ReadEntitySamplePropertyValuesWithGroups,
            ReadActionProperties,
            ReadActionSamplePropertyValues,
        ]

        class ReadTaxonomyToolArgsWithGroups(BaseModel):
            query: ReadTaxonomyQueryWithGroups = Field(..., discriminator="kind")

        return cls(
            team=team,
            user=user,
            state=state,
            config=config,
            node_path=node_path,
            args_schema=ReadTaxonomyToolArgsWithGroups,
            context_manager=context_manager,
        )