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.4 KB
Raw Blame
from typing import Literal, Union

from pydantic import BaseModel, Field

from posthog.event_usage import EventSource
from posthog.models import Team, User
from posthog.taxonomy.dynamic_properties import PropertyScope, dynamic_property_patterns, format_dynamic_property_lines

from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit
from ee.hogai.chat_agent.taxonomy.entities import resolve_entity_name
from ee.hogai.utils.helpers import format_events_yaml, get_event_description, get_event_owner

ENTITY_FIELD_DESCRIPTION = (
    "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. "
    "The plural form of any of these is accepted too."
)


class ReadEvents(BaseModel):
    """Returns the list of available events. Events are sorted by their popularity where the most popular events are at the top."""

    kind: Literal["events"] = "events"
    limit: int = Field(default=500, ge=1, le=500, description="Number of events to return per page.")
    offset: int = Field(default=0, ge=0, description="Number of events to skip for pagination.")


class ReadEventProperties(BaseModel):
    """Returns the description and owner (if set) and properties list for a provided event. Before calling this tool, ensure the event exists by reading events."""

    kind: Literal["event_properties"] = "event_properties"
    event_name: str = Field(description="The name of the event that you want to retrieve properties for.")


class ReadEntityProperties(BaseModel):
    """Returns the properties list for a provided entity."""

    kind: Literal["entity_properties"] = "entity_properties"
    entity: str = Field(description=ENTITY_FIELD_DESCRIPTION)
    # Keep entity as string to allow for dynamic entity types.


class ReadActionProperties(BaseModel):
    """Returns the properties list for a provided action. Before calling this tool, ensure the action exists by searching actions or if it was provided in the context."""

    kind: Literal["action_properties"] = "action_properties"
    action_id: int


class ReadEntitySamplePropertyValues(BaseModel):
    """For a provided entity and a property, returns a list of maximum 25 sample values that the combination has."""

    kind: Literal["entity_property_values"] = "entity_property_values"
    entity: str = Field(description=ENTITY_FIELD_DESCRIPTION)
    # Keep entity as string to allow for dynamic entity types.
    property_name: str = Field(description="Verified property name of an entity.")


class ReadEventSamplePropertyValues(BaseModel):
    """For a provided event and a property, returns a list of maximum 25 sample values that the combination has."""

    kind: Literal["event_property_values"] = "event_property_values"
    event_name: str = Field(description="Verified event name")
    property_name: str = Field(description="Verified property name of an event.")


class ReadActionSamplePropertyValues(BaseModel):
    """For a provided event and a property, returns a list of maximum 25 sample values that the combination has."""

    kind: Literal["action_property_values"] = "action_property_values"
    action_id: int = Field(description="Verified action ID")
    property_name: str = Field(description="Verified property name of an action.")


ReadTaxonomyQuery = Union[
    ReadEvents,
    ReadEventProperties,
    ReadEventSamplePropertyValues,
    ReadEntityProperties,
    ReadEntitySamplePropertyValues,
    ReadActionProperties,
    ReadActionSamplePropertyValues,
]


class ReadTaxonomyToolArgs(BaseModel):
    query: ReadTaxonomyQuery = Field(..., discriminator="kind")


def _dynamic_properties_hint(scope: PropertyScope) -> str:
    """List the dynamic property names of one scope, so the agent can build one it cannot look up.

    Generated from `DYNAMIC_PROPERTY_PATTERNS` rather than written out, because the HogQL taxonomy
    check reads the same list. A name documented here but missing there gets reported back to the
    caller as unknown, which reads as a broken taxonomy.
    """
    return "\n".join(
        [
            f"NOTE: Some {scope} properties follow dynamic naming patterns and will NOT appear in the list above.",
            "Each name below ends in an id or a key, so construct it yourself when the user's question needs it:",
            format_dynamic_property_lines(dynamic_property_patterns(scope)),
        ]
    )


DYNAMIC_PERSON_PROPERTIES_HINT = _dynamic_properties_hint("person")

DYNAMIC_EVENT_PROPERTIES_HINT = _dynamic_properties_hint("event")


def execute_taxonomy_query(
    query: ReadTaxonomyQuery,
    toolkit: TaxonomyAgentToolkit,
    team: Team,
    user: User,
    event_source: EventSource = EventSource.POSTHOG_AI,
) -> str:
    """
    Execute a taxonomy query and return the result.

    This is the shared execution logic used by both internal and external tools.
    """
    match query:
        case ReadEvents():
            return format_events_yaml([], team, user, limit=query.limit, offset=query.offset, event_source=event_source)
        case ReadEventProperties():
            result = toolkit.retrieve_event_or_action_properties(query.event_name)
            description = get_event_description(team, query.event_name)
            prefix = f"Description of `{query.event_name}`: {description}\n\n" if description else ""
            if owner := get_event_owner(team, query.event_name):
                prefix += f"Owner of `{query.event_name}`: {owner}\n\n"
            return f"{prefix}{result}\n\n{DYNAMIC_EVENT_PROPERTIES_HINT}"
        case ReadEventSamplePropertyValues():
            return toolkit.retrieve_event_or_action_property_values(query.event_name, query.property_name)
        case ReadActionProperties():
            result = toolkit.retrieve_event_or_action_properties(query.action_id)
            return f"{result}\n\n{DYNAMIC_EVENT_PROPERTIES_HINT}"
        case ReadActionSamplePropertyValues():
            return toolkit.retrieve_event_or_action_property_values(query.action_id, query.property_name)
        case ReadEntityProperties():
            result = toolkit.retrieve_entity_properties(query.entity)
            if resolve_entity_name(query.entity, ["person"]) == "person":
                return f"{result}\n\n{DYNAMIC_PERSON_PROPERTIES_HINT}"
            return result
        case ReadEntitySamplePropertyValues():
            return toolkit.retrieve_entity_property_values(query.entity, query.property_name)
        case _:
            raise ValueError(f"Invalid query type: The query structure '{type(query).__name__}' is not recognized.")