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.

fix(ph-ai): correct usage command reporting (#58862)

Alessandro Pogliaghi9af3046458d0
diff --git a/ee/hogai/chat_agent/prompt_builder.py b/ee/hogai/chat_agent/prompt_builder.py
index 3cde9b4e288a..973064dc0e0f 100644
--- a/ee/hogai/chat_agent/prompt_builder.py
+++ b/ee/hogai/chat_agent/prompt_builder.py
@@ -11,6 +11,7 @@ from ee.hogai.chat_agent.prompts import (
PROACTIVENESS_PROMPT,
PRODUCT_ADVOCACY_PROMPT,
ROLE_PROMPT,
+ SLASH_COMMANDS_PROMPT,
SWITCHING_MODES_PROMPT,
SWITCHING_TO_PLAN_PROMPT,
TASK_MANAGEMENT_PROMPT,
@@ -77,6 +78,7 @@ class ChatAgentPlanPromptBuilder(AgentPromptBuilderBase):
tone_and_style=TONE_AND_STYLE_PROMPT,
writing_style=WRITING_STYLE_PROMPT,
basic_functionality=BASIC_FUNCTIONALITY_PROMPT,
+ slash_commands=SLASH_COMMANDS_PROMPT,
switching_modes=SWITCHING_MODES_PROMPT,
task_management=TASK_MANAGEMENT_PROMPT,
onboarding_task=CHAT_ONBOARDING_TASK_PROMPT,
@@ -115,6 +117,7 @@ class ChatAgentPromptBuilder(AgentPromptBuilderBase):
writing_style=WRITING_STYLE_PROMPT,
proactiveness=PROACTIVENESS_PROMPT,
basic_functionality=BASIC_FUNCTIONALITY_PROMPT,
+ slash_commands=SLASH_COMMANDS_PROMPT,
switching_modes=SWITCHING_MODES_PROMPT,
task_management=TASK_MANAGEMENT_PROMPT,
doing_tasks=DOING_TASKS_PROMPT,
diff --git a/ee/hogai/chat_agent/prompts/__init__.py b/ee/hogai/chat_agent/prompts/__init__.py
index fbb55bd04a47..304b81f9df1d 100644
--- a/ee/hogai/chat_agent/prompts/__init__.py
+++ b/ee/hogai/chat_agent/prompts/__init__.py
@@ -7,6 +7,7 @@ from ee.hogai.chat_agent.prompts.base import (
PROACTIVENESS_PROMPT,
PRODUCT_ADVOCACY_PROMPT,
ROLE_PROMPT,
+ SLASH_COMMANDS_PROMPT,
SWITCHING_MODES_PROMPT,
TASK_MANAGEMENT_PROMPT,
TONE_AND_STYLE_PROMPT,
@@ -41,6 +42,7 @@ __all__ = [
"ROOT_BILLING_CONTEXT_WITH_ACCESS_PROMPT",
"ROOT_BILLING_CONTEXT_WITH_NO_ACCESS_PROMPT",
"ROOT_GROUPS_PROMPT",
+ "SLASH_COMMANDS_PROMPT",
"SWITCHING_MODES_PROMPT",
"TASK_MANAGEMENT_PROMPT",
"TONE_AND_STYLE_PROMPT",
diff --git a/ee/hogai/chat_agent/prompts/base.py b/ee/hogai/chat_agent/prompts/base.py
index 66016d3984f2..08058b8675ca 100644
--- a/ee/hogai/chat_agent/prompts/base.py
+++ b/ee/hogai/chat_agent/prompts/base.py
@@ -74,6 +74,19 @@ When users ask about SQL variables or query variables, use SQL mode and query `s
</basic_functionality>
""".strip()
+SLASH_COMMANDS_PROMPT = """
+<slash_commands>
+PostHog AI supports slash commands. They are real app features handled by PostHog when users send a message starting with one of these commands:
+- `/init` - Set up knowledge about the user's product and business.
+- `/remember [information]` - Append information verbatim to project-level core memory.
+- `/usage` - Show PostHog AI credit usage for the current conversation and billing period. Do not claim this command is fabricated, unavailable, or made up.
+- `/feedback [feedback]` - Send feedback about the PostHog AI experience.
+- `/ticket` - Create a support ticket from the current conversation when enough context is available.
+
+If a user asks about one of these commands, explain what the command does. If they report a command result looks wrong, treat the command as real and help debug the result.
+</slash_commands>
+""".strip()
+
SWITCHING_MODES_PROMPT = """
<switching_modes>
You can switch between specialized modes that provide different tools and capabilities for specific task types. All modes share access to common tools (memory, todo management), but each mode has unique specialized instructions and tools.
@@ -240,6 +253,8 @@ AGENT_PROMPT = """
{{{basic_functionality}}}
+{{{slash_commands}}}
+
{{{switching_modes}}}
{{{task_management}}}
@@ -260,11 +275,6 @@ AGENT_PROMPT = """
AGENT_CORE_MEMORY_PROMPT = """
{{{core_memory}}}
New memories will automatically be added to the core memory as the conversation progresses. If users ask to save, update, or delete the core memory, say you have done it. If the '/remember [information]' command is used, the information gets appended verbatim to core memory.
-
-Available slash commands:
-- '/init' - Set up knowledge about the user's product and business
-- '/remember [information]' - Adds information to the project-level core memory
-- '/usage' - Shows PostHog AI credit usage for the current conversation and billing period
""".strip()
CONTEXTUAL_TOOLS_REMINDER_PROMPT = """
diff --git a/ee/hogai/chat_agent/prompts/plan.py b/ee/hogai/chat_agent/prompts/plan.py
index 2985152a820f..bc4f174df627 100644
--- a/ee/hogai/chat_agent/prompts/plan.py
+++ b/ee/hogai/chat_agent/prompts/plan.py
@@ -9,6 +9,8 @@ CHAT_PLAN_AGENT_PROMPT = """
{{{basic_functionality}}}
+{{{slash_commands}}}
+
{{{switching_modes}}}
{{{task_management}}}
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
index 67d3a7c0e45d..144b148120bd 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
@@ -7,6 +7,7 @@ import posthoganalytics
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.group_type_mapping import get_group_types_for_team
from posthog.tasks.usage_report import (
AI_BILLING_EXCLUDED_TOOLS,
AI_COST_MARKUP_PERCENT,
@@ -29,6 +30,24 @@ CH_BILLING_SETTINGS = {
"max_execution_time": 60, # 1 minute
}
+# Name of the group type whose value is the customer cloud URL (e.g. https://eu.posthog.com).
+# Sent via `event_usage.groups(...)` when capturing $ai_trace / $ai_generation events.
+INSTANCE_GROUP_TYPE = "instance"
+
+
+def _get_instance_group_type_index(team_id: int) -> int | None:
+ """Resolve the $group_N index that holds the cloud URL for the given internal AI events team.
+
+ group_type_index is assigned in the order group types were registered per project,
+ so the same `instance` group lives at different indexes between the EU (team 1)
+ and US (team 2) internal projects.
+ """
+ for mapping in get_group_types_for_team(team_id):
+ if mapping.get("group_type") == INSTANCE_GROUP_TYPE:
+ index = mapping.get("group_type_index")
+ return int(index) if index is not None else None
+ return None
+
def _get_billing_config_payload() -> dict | None:
"""
@@ -132,9 +151,16 @@ def get_ai_credits(
region_value = region if region in CLOUD_REGION_TO_TEAM_ID else "EU"
team_to_query = CLOUD_REGION_TO_TEAM_ID[region_value]
- # Only filter by region in production (EU/US) - local dev events don't have region set
+ # Only filter by region in production (EU/US) - local dev events don't have region set.
+ # The $group_N index for the `instance` group differs across internal projects,
+ # so resolve it from the destination team rather than hard-coding $group_1.
is_production = region in ["EU", "US"]
- region_filter = "AND JSONExtractString(properties, '$group_1') = %(region_url)s" if is_production else ""
+ instance_group_index = _get_instance_group_type_index(team_to_query) if is_production else None
+ region_filter = (
+ f"AND JSONExtractString(properties, '$group_{instance_group_index}') = %(region_url)s"
+ if instance_group_index is not None
+ else ""
+ )
# Session filter expression for PREWHERE (must NOT use alias)
session_filter_prewhere = (
@@ -253,7 +279,7 @@ def get_ai_credits(
"excluded_tools": AI_BILLING_EXCLUDED_TOOLS,
}
- if is_production:
+ if instance_group_index is not None:
params["region_url"] = CLOUD_REGION_TO_URL[region_value]
if conversation_id:
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
index 312fe1cc6472..dc657471b207 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py
@@ -5,10 +5,15 @@ from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import patch
+from parameterized import parameterized
+
from ee.hogai.chat_agent.slash_commands.commands.usage.queries import (
+ CLOUD_REGION_TO_TEAM_ID,
+ CLOUD_REGION_TO_URL,
DEFAULT_FREE_TIER_CREDITS,
DEFAULT_GA_LAUNCH_DATE,
format_usage_message,
+ get_ai_credits,
get_ai_free_tier_credits,
get_conversation_start_time,
get_ga_launch_date,
@@ -72,6 +77,86 @@ class TestUsage(BaseTest):
credits = get_ai_free_tier_credits(team_id=1)
self.assertEqual(credits, DEFAULT_FREE_TIER_CREDITS)
+ @parameterized.expand(
+ [
+ ("eu_cloud", "EU", CLOUD_REGION_TO_TEAM_ID["EU"], CLOUD_REGION_TO_URL["EU"], 2),
+ ("us_cloud", "US", CLOUD_REGION_TO_TEAM_ID["US"], CLOUD_REGION_TO_URL["US"], 1),
+ ("local_dev", None, CLOUD_REGION_TO_TEAM_ID["EU"], None, None),
+ ]
+ )
+ def test_get_ai_credits_scopes_ai_events_query(
+ self,
+ _name,
+ region,
+ expected_team_to_query,
+ expected_region_url,
+ instance_group_index,
+ ):
+ begin = datetime(2026, 5, 1, tzinfo=UTC)
+ end = datetime(2026, 5, 2, tzinfo=UTC)
+ conversation_id = uuid4()
+
+ group_mappings = (
+ [
+ {"group_type": "organization", "group_type_index": 0},
+ {"group_type": "instance", "group_type_index": instance_group_index},
+ ]
+ if instance_group_index is not None
+ else []
+ )
+
+ with (
+ patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_instance_region") as mock_region,
+ patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.sync_execute") as mock_sync_execute,
+ patch(
+ "ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_group_types_for_team"
+ ) as mock_group_types,
+ ):
+ mock_region.return_value = region
+ mock_sync_execute.return_value = [(42,)]
+ mock_group_types.return_value = group_mappings
+
+ credits = get_ai_credits(team_id=133393, begin=begin, end=end, conversation_id=conversation_id)
+
+ self.assertEqual(credits, 42)
+ query, params = mock_sync_execute.call_args[0][:2]
+ self.assertEqual(params["team_to_query"], expected_team_to_query)
+ self.assertEqual(params["session_id"], str(conversation_id))
+ if expected_region_url is None:
+ self.assertNotIn("region_url", params)
+ self.assertNotIn("%(region_url)s", query)
+ mock_group_types.assert_not_called()
+ else:
+ self.assertEqual(params["region_url"], expected_region_url)
+ mock_group_types.assert_called_once_with(expected_team_to_query)
+ self.assertIn(
+ f"AND JSONExtractString(properties, '$group_{instance_group_index}') = %(region_url)s",
+ query,
+ )
+
+ def test_get_ai_credits_skips_region_filter_when_instance_group_missing(self):
+ """If the destination team has no `instance` group registered, skip the region filter rather than match nothing."""
+ begin = datetime(2026, 5, 1, tzinfo=UTC)
+ end = datetime(2026, 5, 2, tzinfo=UTC)
+ conversation_id = uuid4()
+
+ with (
+ patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_instance_region") as mock_region,
+ patch("ee.hogai.chat_agent.slash_commands.commands.usage.queries.sync_execute") as mock_sync_execute,
+ patch(
+ "ee.hogai.chat_agent.slash_commands.commands.usage.queries.get_group_types_for_team",
+ return_value=[{"group_type": "organization", "group_type_index": 0}],
+ ),
+ ):
+ mock_region.return_value = "EU"
+ mock_sync_execute.return_value = [(0,)]
+
+ get_ai_credits(team_id=133393, begin=begin, end=end, conversation_id=conversation_id)
+
+ query, params = mock_sync_execute.call_args[0][:2]
+ self.assertNotIn("region_url", params)
+ self.assertNotIn("%(region_url)s", query)
+
def test_get_conversation_start_time_exists(self):
"""Test retrieving conversation start time for existing conversation."""
conversation = Conversation.objects.create(
diff --git a/ee/hogai/chat_agent/test/test_mode_manager.py b/ee/hogai/chat_agent/test/test_mode_manager.py
index 5669a186381d..a49c5e8865c0 100644
--- a/ee/hogai/chat_agent/test/test_mode_manager.py
+++ b/ee/hogai/chat_agent/test/test_mode_manager.py
@@ -255,6 +255,39 @@ class TestAgentToolkit(BaseTest):
self.assertNotIn("Switch to `plan` mode", system_prompt)
self.assertNotIn("When to switch to plan mode", system_prompt)
+ def test_prompt_builder_includes_slash_commands(self):
+ context_manager = AssistantContextManager(
+ team=self.team, user=self.user, config=RunnableConfig(configurable={})
+ )
+ prompt_builder = ChatAgentPromptBuilder(team=self.team, user=self.user, context_manager=context_manager)
+ system_prompt = prompt_builder._get_system_prompt()
+
+ self.assertIn("PostHog AI supports slash commands", system_prompt)
+ self.assertIn("`/usage`", system_prompt)
+ self.assertIn("Do not claim this command is fabricated", system_prompt)
+
+ async def test_plan_prompt_builder_includes_slash_commands(self):
+ context_manager = AssistantContextManager(
+ team=self.team, user=self.user, config=RunnableConfig(configurable={})
+ )
+ prompt_builder = ChatAgentPlanPromptBuilder(team=self.team, user=self.user, context_manager=context_manager)
+
+ with (
+ patch.object(prompt_builder, "_get_billing_prompt", new=AsyncMock(return_value="")),
+ patch.object(prompt_builder, "_aget_core_memory_text", new=AsyncMock(return_value="")),
+ patch.object(context_manager, "get_group_names", new=AsyncMock(return_value=[])),
+ patch("ee.hogai.chat_agent.prompt_builder._get_default_tools_prompt", new=AsyncMock(return_value="")),
+ patch("ee.hogai.chat_agent.prompt_builder._get_modes_prompt", new=AsyncMock(return_value="")),
+ patch("ee.hogai.chat_agent.mode_manager.get_execution_mode_registry", return_value={}),
+ ):
+ messages = await prompt_builder.get_prompts(AssistantState(messages=[]), RunnableConfig(configurable={}))
+
+ system_prompt = "\n\n".join(str(message.content) for message in messages if isinstance(message, SystemMessage))
+
+ self.assertIn("PostHog AI supports slash commands", system_prompt)
+ self.assertIn("`/usage`", system_prompt)
+ self.assertIn("Do not claim this command is fabricated", system_prompt)
+
class TestChatAgentModeManagerPlanMode(BaseTest):
def test_plan_mode_sets_supermode_and_mode(self):