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.

15.7 KB
Raw Blame
from collections.abc import Callable

from posthog.test.base import BaseTest
from unittest.mock import patch

from langchain_core.agents import AgentAction
from parameterized import parameterized
from pydantic import BaseModel

from posthog.schema import ActorsPropertyTaxonomyQuery, AssistantToolCall

from posthog.models import Team

from products.event_definitions.backend.models.property_definition import PropertyDefinition

from ee.hogai.chat_agent.taxonomy.toolkit import TaxonomyAgentToolkit, TaxonomyToolNotFoundError
from ee.hogai.chat_agent.taxonomy.tools import TaxonomyTool
from ee.hogai.chat_agent.taxonomy.virtual_properties import PropertyDefinitionOrVirtual


class DummyToolkit(TaxonomyAgentToolkit):
    def get_tools(self):
        return self._get_default_tools()


class TestTaxonomyAgentToolkit(BaseTest):
    def setUp(self):
        super().setUp()
        self.toolkit = DummyToolkit(self.team, self.user)

    async def test_toolkit_initialization(self):
        self.assertEqual(self.toolkit._team, self.team)
        self.assertIsInstance(await self.toolkit._get_entity_names(), list)

    @parameterized.expand(
        [
            ("person", ["person", "session"]),
            ("session", ["person", "session"]),
        ]
    )
    async def test_entity_names_basic(self, entity, expected_base):
        self.assertIn(entity, await self.toolkit._get_entity_names())
        for expected in expected_base:
            self.assertIn(expected, await self.toolkit._get_entity_names())

    def test_enrich_props_with_descriptions(self):
        props = [("$browser", "String"), ("custom_prop", "Numeric")]
        enriched = self.toolkit._enrich_props_with_descriptions("event", props)

        browser_prop = next((p for p in enriched if p[0] == "$browser"), None)
        self.assertIsNotNone(browser_prop)
        assert browser_prop is not None
        self.assertEqual(browser_prop[1], "String")
        self.assertIsNotNone(browser_prop[2])

    def test_enrich_props_uses_stored_description_only_for_custom_props(self):
        # Custom properties fall back to the user-authored description; core taxonomy still wins so a
        # stored description can never override (or spoof) a built-in one.
        props = [("$browser", "String"), ("custom_prop", "Numeric")]
        stored = {"custom_prop": "Revenue in cents", "$browser": "should be ignored"}
        enriched = self.toolkit._enrich_props_with_descriptions("event", props, stored)
        by_name = {name: description for name, _, description in enriched}

        self.assertEqual(by_name["custom_prop"], "Revenue in cents")
        self.assertNotEqual(by_name["$browser"], "should be ignored")

    @parameterized.expand(
        [
            ([], 0, False, "The property does not have any values"),
            (["value1", "value2"], None, False, "- value1\n- value2\n- and many more distinct values"),
            (["value1", "value2"], 5, False, "- value1\n- value2\n- and 3 more distinct values"),
            (["string_val"], 1, True, '"string_val"'),
            ([1.0, 2.0], 2, False, "'1'\n- '2'"),
        ]
    )
    def test_format_property_values(self, sample_values, sample_count, format_as_string, expected_substring):
        result = self.toolkit._format_property_values("test_property", sample_values, sample_count, format_as_string)
        self.assertIn(expected_substring, result)

    def test_handle_incorrect_response(self):
        class TestModel(BaseModel):
            field: str = "test"

        response = TestModel()
        result = self.toolkit.handle_incorrect_response(response)
        self.assertIn("test", result)

    @parameterized.expand(
        [
            ("retrieve_entity_properties", {"entity": "person"}, "mocked"),
            ("retrieve_entity_property_values", {"entity": "person", "property_name": "email"}, "mocked"),
            ("retrieve_event_properties", {"event_name": "test_event"}, "mocked"),
            ("retrieve_event_property_values", {"event_name": "test_event", "property_name": "$browser"}, "mocked"),
        ]
    )
    @patch.object(DummyToolkit, "retrieve_entity_properties_parallel", return_value={"person": "mocked"})
    @patch.object(DummyToolkit, "retrieve_entity_property_values", return_value={"person": ["mocked"]})
    @patch.object(DummyToolkit, "retrieve_event_or_action_properties_parallel", return_value={"test_event": "mocked"})
    @patch.object(DummyToolkit, "retrieve_event_or_action_property_values", return_value={"test_event": ["mocked"]})
    async def test_handle_tools(self, tool_name, tool_args, expected_result, *mocks):
        class Arguments(BaseModel):
            pass

        for key, value in tool_args.items():
            setattr(Arguments, key, value)

        class ToolInput(TaxonomyTool):
            name: str
            arguments: Arguments

        tool_input = ToolInput(name=tool_name, arguments=Arguments(**tool_args))
        result = await self.toolkit.handle_tools({tool_name: [(tool_input, "test_call_id")]})

        self.assertEqual(len(result), 1)
        self.assertEqual(result["test_call_id"], expected_result)

    async def test_handle_tools_invalid_tool(self):
        class ToolInput(TaxonomyTool):
            name: str = "invalid_tool"
            arguments: dict = {}

        tool_input = ToolInput()

        with self.assertRaises(TaxonomyToolNotFoundError):
            await self.toolkit.handle_tools({"invalid_tool": [(tool_input, "invalid_tool")]})

    def test_format_properties_formats(self):
        props: list[tuple[str, str | None, str | None]] = [
            ("prop1", "String", "Test description"),
            ("prop2", "Numeric", None),
        ]

        # Test XML format
        xml_result = self.toolkit._format_properties_xml(props)
        self.assertIn("<properties>", xml_result)
        self.assertIn("<String>", xml_result)
        self.assertIn("<Numeric>", xml_result)
        self.assertIn("<name>prop1</name>", xml_result)
        self.assertIn("<description>Test description</description>", xml_result)
        self.assertIn("<name>prop2</name>", xml_result)

        # Test YAML format
        yaml_result = self.toolkit._format_properties_yaml(props)
        self.assertIn("properties:", yaml_result)
        self.assertIn("String:", yaml_result)
        self.assertIn("Numeric:", yaml_result)
        self.assertIn("name: prop1", yaml_result)
        self.assertIn("description: Test description", yaml_result)

    @parameterized.expand(
        [
            (
                "retrieve_entity_properties_parallel",
                {"entity": "person"},
                "retrieve_entity_properties_parallel",
                {"entity": "person"},
            ),
            (
                "retrieve_event_properties",
                {"event_name": "test_event"},
                "retrieve_event_properties",
                {"event_name": "test_event"},
            ),
            (
                "ask_user_for_help",
                {"request": "Can you help me?"},
                "ask_user_for_help",
                {"request": "Can you help me?"},
            ),
            (
                "retrieve_entity_property_values",
                {"entity": "person", "property_name": "email"},
                "retrieve_entity_property_values",
                {"entity": "person", "property_name": "email"},
            ),
            (
                "retrieve_event_property_values",
                {"event_name": "test_event", "property_name": "$browser"},
                "retrieve_event_property_values",
                {"event_name": "test_event", "property_name": "$browser"},
            ),
            (
                "retrieve_entity_properties_parallel",
                {"entity": "session"},
                "retrieve_entity_properties_parallel",
                {"entity": "session"},
            ),
        ]
    )
    def test_get_tool_input_model_with_valid_tools(self, tool_name, tool_input, expected_name, expected_args):
        """Test get_tool_input_model with various valid tools."""
        action = AgentAction(tool=tool_name, tool_input=tool_input, log="test log")

        result = self.toolkit.get_tool_input_model(action)

        self.assertEqual(result.name, expected_name)
        self.assertIsInstance(result.arguments, BaseModel)

        # Check that all expected arguments are present and correct
        for key, value in expected_args.items():
            self.assertEqual(getattr(result.arguments, key), value)

    def test_get_tool_input_model_with_custom_tools(self):
        """Test get_tool_input_model when custom tools are available."""

        # Create a custom toolkit with custom tools
        class CustomToolkit(TaxonomyAgentToolkit):
            def _get_custom_tools(self):
                class CustomTool(BaseModel):
                    custom_field: str

                return [CustomTool]

        custom_toolkit = CustomToolkit(self.team, self.user)

        action = AgentAction(tool="custom_tool", tool_input={"custom_field": "test_value"}, log="test log")

        result = custom_toolkit.get_tool_input_model(action)

        self.assertEqual(result.name, "custom_tool")
        self.assertEqual(result.arguments.custom_field, "test_value")  # type: ignore[union-attr]
        self.assertIsInstance(result.arguments, BaseModel)

    def test_get_tools_handles_not_implemented_error(self):
        """Test that get_tools properly handles NotImplementedError from _get_custom_tools."""

        # Create a toolkit that doesn't override _get_custom_tools
        class BasicToolkit(TaxonomyAgentToolkit):
            def _get_custom_tools(self):
                raise NotImplementedError("This is a test error")

        basic_toolkit = BasicToolkit(self.team, self.user)

        # Should not raise NotImplementedError, should fall back to default tools
        tools = basic_toolkit.get_tools()

        # Verify we get the default tools (should contain the standard taxonomy tools)
        self.assertIsInstance(tools, list)
        self.assertGreater(len(tools), 0)

        tool_names = [tool.__name__ for tool in tools]
        expected_tools = [
            "retrieve_event_properties",
            "retrieve_entity_properties",
            "retrieve_entity_property_values",
            "retrieve_event_property_values",
            "ask_user_for_help",
        ]

        for expected_tool in expected_tools:
            self.assertIn(expected_tool, tool_names)

    def test_get_tools_with_custom_tools(self):
        """Test that get_tools properly combines default and custom tools."""

        class CustomToolkit(TaxonomyAgentToolkit):
            def _get_custom_tools(self):
                # Return some mock custom tools
                def custom_tool_1():
                    pass

                def custom_tool_2():
                    pass

                return [custom_tool_1, custom_tool_2]

        custom_toolkit = CustomToolkit(self.team, self.user)

        # Should return both default and custom tools
        tools = custom_toolkit.get_tools()

        # Verify we get both default and custom tools
        self.assertIsInstance(tools, list)
        self.assertGreater(len(tools), 0)

        # Get tool names
        tool_names = [tool.__name__ for tool in tools]

        expected_default_tools = [
            "retrieve_event_properties",
            "retrieve_entity_properties",
            "retrieve_entity_property_values",
            "retrieve_event_property_values",
            "ask_user_for_help",
        ]

        for expected_tool in expected_default_tools:
            self.assertIn(expected_tool, tool_names)

        # Verify custom tools are present
        expected_custom_tools = ["custom_tool_1", "custom_tool_2"]

        for expected_tool in expected_custom_tools:
            self.assertIn(expected_tool, tool_names)

        self.assertEqual(len(tools), len(expected_default_tools) + len(expected_custom_tools))

    @patch("ee.hogai.chat_agent.taxonomy.toolkit.restricted_property_names")
    async def test_handle_entity_properties_excludes_restricted(self, mock_restricted):
        mock_restricted.return_value = {"secret"}
        await PropertyDefinition.objects.acreate(
            team=self.team, type=PropertyDefinition.Type.PERSON, name="secret", property_type="String"
        )
        await PropertyDefinition.objects.acreate(
            team=self.team, type=PropertyDefinition.Type.PERSON, name="visible", property_type="String"
        )
        task = AssistantToolCall(id="1", name="retrieve_entity_properties", args={"entity": "person"})
        result = await self.toolkit._handle_entity_properties_task({"task": task})
        self.assertIn("<name>visible</name>", result.result)
        self.assertNotIn("<name>secret</name>", result.result)

    async def test_person_properties_surface_stored_descriptions_sanitized(self):
        from ee.models.property_definition import EnterprisePropertyDefinition

        # An EnterprisePropertyDefinition also creates the base PropertyDefinition row the person path
        # discovers, so its user-authored description should ride along on the surfaced property.
        await EnterprisePropertyDefinition.objects.acreate(
            team=self.team,
            type=PropertyDefinition.Type.PERSON,
            name="plan_tier",
            property_type="String",
            description="Subscription tier\nof the account",
        )
        task = AssistantToolCall(id="1", name="retrieve_entity_properties", args={"entity": "person"})
        result = await self.toolkit._handle_entity_properties_task({"task": task})

        self.assertIn("<name>plan_tier</name>", result.result)
        # Sanitization collapses the newline so a description can't break out of its line.
        self.assertIn("<description>Subscription tier of the account</description>", result.result)

    @parameterized.expand(
        [
            (
                "entity_lookup",
                PropertyDefinition.Type.PERSON,
                lambda toolkit: vars(TaxonomyAgentToolkit)["_get_definitions_for_entity"].func(
                    toolkit, "person", ["sibling_tier"], ActorsPropertyTaxonomyQuery(properties=["sibling_tier"])
                ),
            ),
            (
                "event_or_action_lookup",
                PropertyDefinition.Type.EVENT,
                lambda toolkit: vars(TaxonomyAgentToolkit)["_get_definitions_for_event_or_action"].func(
                    toolkit, ["sibling_tier"]
                ),
            ),
        ]
    )
    def test_property_definitions_resolve_across_sibling_environments(
        self,
        _name: str,
        definition_type: PropertyDefinition.Type,
        lookup: Callable[[TaxonomyAgentToolkit], dict[str, PropertyDefinitionOrVirtual]],
    ) -> None:
        # Both lookups are `database_sync_to_async(thread_sensitive=False)`, which runs them on another thread and
        # connection. The wrapper's `.func` runs them on the test's connection, the only one that sees its rows.
        sibling = Team.objects.create(organization=self.organization, project=self.team.project)
        PropertyDefinition.objects.create(
            team=sibling,
            project=self.team.project,
            type=definition_type,
            name="sibling_tier",
            property_type="String",
        )

        definition = lookup(self.toolkit)["sibling_tier"]

        assert isinstance(definition, PropertyDefinition)
        self.assertEqual(definition.property_type, "String")

    @patch("ee.hogai.chat_agent.taxonomy.toolkit.restricted_property_names")
    async def test_retrieve_multiple_entity_property_values_hides_restricted(self, mock_restricted):
        mock_restricted.return_value = {"secret"}
        results = await self.toolkit._retrieve_multiple_entity_property_values("person", ["secret"])
        self.assertEqual(len(results), 1)
        self.assertIn("No values found for property secret", results[0])