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(phai): mark slash command output as system-generated in LLM history (#60104)

Christiaan Hendriksen484c62fead0d
diff --git a/ee/hogai/chat_agent/slash_commands/nodes.py b/ee/hogai/chat_agent/slash_commands/nodes.py
index 8171f425f2b7..beef17d019c8 100644
--- a/ee/hogai/chat_agent/slash_commands/nodes.py
+++ b/ee/hogai/chat_agent/slash_commands/nodes.py
@@ -1,7 +1,7 @@
from langchain_core.runnables import RunnableConfig
from langgraph.types import Send
-from posthog.schema import HumanMessage
+from posthog.schema import AssistantMessage, AssistantMessageMetadata, HumanMessage
from ee.hogai.chat_agent.memory.nodes import MemoryOnboardingNode
from ee.hogai.chat_agent.slash_commands.commands import SlashCommand
@@ -12,7 +12,7 @@ from ee.hogai.chat_agent.slash_commands.commands.usage import UsageCommand
from ee.hogai.core.agent_modes.const import SlashCommandName
from ee.hogai.core.node import AssistantNode
from ee.hogai.utils.types import AssistantState, PartialAssistantState
-from ee.hogai.utils.types.base import AssistantNodeName
+from ee.hogai.utils.types.base import AssistantMessageUnion, AssistantNodeName
class SlashCommandHandlerNode(AssistantNode):
@@ -51,7 +51,26 @@ class SlashCommandHandlerNode(AssistantNode):
command_class = self.COMMAND_HANDLERS[command]
command_instance = command_class(self._team, self._user)
- return await command_instance.execute(config, state)
+ result = await command_instance.execute(config, state)
+ return self._stamp_message_source(result, command)
+
+ @staticmethod
+ def _stamp_message_source(result: PartialAssistantState, command: str) -> PartialAssistantState:
+ if not result.messages:
+ return result
+ source = f"slash_command:{command.lstrip('/')}"
+ stamped: list[AssistantMessageUnion] = []
+ for msg in result.messages:
+ if isinstance(msg, AssistantMessage) and (msg.meta is None or msg.meta.source is None):
+ meta = (
+ msg.meta.model_copy(update={"source": source})
+ if msg.meta
+ else AssistantMessageMetadata(source=source)
+ )
+ stamped.append(msg.model_copy(update={"meta": meta}))
+ else:
+ stamped.append(msg)
+ return result.model_copy(update={"messages": stamped})
async def arouter(self, state: AssistantState) -> AssistantNodeName | list[Send]:
"""
diff --git a/ee/hogai/chat_agent/slash_commands/test/test_slash_command_handler.py b/ee/hogai/chat_agent/slash_commands/test/test_slash_command_handler.py
index 9fb8b6d28986..9b73474986f2 100644
--- a/ee/hogai/chat_agent/slash_commands/test/test_slash_command_handler.py
+++ b/ee/hogai/chat_agent/slash_commands/test/test_slash_command_handler.py
@@ -4,8 +4,9 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from langgraph.types import Send
+from parameterized import parameterized
-from posthog.schema import AssistantMessage, HumanMessage
+from posthog.schema import AssistantMessage, AssistantMessageMetadata, HumanMessage
from ee.hogai.chat_agent.slash_commands.commands import SlashCommand
from ee.hogai.chat_agent.slash_commands.commands.feedback import FeedbackCommand
@@ -14,7 +15,7 @@ from ee.hogai.chat_agent.slash_commands.commands.ticket import TicketCommand
from ee.hogai.chat_agent.slash_commands.commands.usage import UsageCommand
from ee.hogai.chat_agent.slash_commands.nodes import SlashCommandHandlerNode
from ee.hogai.core.agent_modes.const import SlashCommandName
-from ee.hogai.utils.types import AssistantState
+from ee.hogai.utils.types import AssistantState, PartialAssistantState
from ee.hogai.utils.types.base import AssistantNodeName
@@ -166,3 +167,37 @@ class TestSlashCommandHandlerNode(BaseTest):
state = AssistantState(messages=[HumanMessage(content="/ticket")])
result = await self.node.arouter(state)
self.assertEqual(result, AssistantNodeName.END)
+
+ @parameterized.expand(
+ [
+ (
+ "no_meta",
+ None,
+ SlashCommandName.FIELD_USAGE,
+ "slash_command:usage",
+ None,
+ ),
+ (
+ "preserves_existing_meta_fields",
+ AssistantMessageMetadata(thinking=[{"type": "thinking", "content": "x"}]),
+ SlashCommandName.FIELD_REMEMBER,
+ "slash_command:remember",
+ [{"type": "thinking", "content": "x"}],
+ ),
+ (
+ "does_not_overwrite_existing_source",
+ AssistantMessageMetadata(source="slash_command:other"),
+ SlashCommandName.FIELD_USAGE,
+ "slash_command:other",
+ None,
+ ),
+ ]
+ )
+ def test_stamp_message_source(self, _name, initial_meta, command, expected_source, expected_thinking):
+ result = PartialAssistantState(messages=[AssistantMessage(content="hi", id="1", meta=initial_meta)])
+ stamped = SlashCommandHandlerNode._stamp_message_source(result, command)
+ msg = stamped.messages[0]
+ assert isinstance(msg, AssistantMessage)
+ assert msg.meta is not None
+ self.assertEqual(msg.meta.source, expected_source)
+ self.assertEqual(msg.meta.thinking, expected_thinking)
diff --git a/ee/hogai/utils/anthropic.py b/ee/hogai/utils/anthropic.py
index f064c5afe44a..8c41db57cc9f 100644
--- a/ee/hogai/utils/anthropic.py
+++ b/ee/hogai/utils/anthropic.py
@@ -45,6 +45,19 @@ def convert_context_message_to_anthropic_message(message: ContextMessage) -> mes
return messages.HumanMessage(content=[{"type": "text", "text": message.content}])
+def _get_provenance_note(message: AssistantMessage) -> str | None:
+ if not message.meta or not message.meta.source:
+ return None
+ source = message.meta.source
+ if source.startswith("slash_command:"):
+ command_name = source.split(":", 1)[1]
+ return (
+ f"[System note: the previous assistant message was produced by the /{command_name} slash command. "
+ "It is deterministic PostHog code, not assistant-authored content.]"
+ )
+ return None
+
+
def convert_assistant_message_to_anthropic_message(
message: AssistantMessage, tool_result_map: Mapping[str, AssistantToolCallMessage]
) -> list[messages.BaseMessage]:
@@ -76,6 +89,12 @@ def convert_assistant_message_to_anthropic_message(
),
)
+ # Provenance note goes as a follow-up HumanMessage rather than prefilling the AIMessage
+ # — prefilling assistant content isn't supported in Sonnet 4.6+.
+ provenance_note = _get_provenance_note(message)
+ if provenance_note:
+ history.append(messages.HumanMessage(content=[{"type": "text", "text": provenance_note}]))
+
return history
diff --git a/ee/hogai/utils/test/test_anthropic.py b/ee/hogai/utils/test/test_anthropic.py
index c75801e887a1..9ce55c35b102 100644
--- a/ee/hogai/utils/test/test_anthropic.py
+++ b/ee/hogai/utils/test/test_anthropic.py
@@ -5,7 +5,11 @@ from parameterized import parameterized
from posthog.schema import AssistantMessage, AssistantMessageMetadata
-from ee.hogai.utils.anthropic import add_cache_control, get_anthropic_thinking_from_assistant_message
+from ee.hogai.utils.anthropic import (
+ add_cache_control,
+ convert_assistant_message_to_anthropic_message,
+ get_anthropic_thinking_from_assistant_message,
+)
class TestAnthropicUtils(BaseTest):
@@ -104,3 +108,36 @@ class TestAnthropicUtils(BaseTest):
self.assertEqual(message.content[1]["type"], "image")
self.assertEqual(message.content[1]["url"], "http://example.com/image.jpg")
self.assertEqual(message.content[1]["cache_control"], {"type": "ephemeral", "ttl": "5m"})
+
+ @parameterized.expand(
+ [
+ ("no_source", None, "Original content", None),
+ ("slash_command_usage", "slash_command:usage", "Current conversation: 5 credits", "usage"),
+ ("slash_command_remember", "slash_command:remember", "Saved memory", "remember"),
+ ("unknown_source", "unknown_source", "Original content", None),
+ ]
+ )
+ def test_convert_assistant_message_provenance_note(self, _name, source, content_text, expected_command):
+ meta = AssistantMessageMetadata(source=source) if source else None
+ message = AssistantMessage(content=content_text, id="1", meta=meta)
+ result = convert_assistant_message_to_anthropic_message(message, {})
+
+ # Assistant text is never modified — only a follow-up HumanMessage is appended when there's a slash-command source.
+ ai_message = result[0]
+ ai_content = ai_message.content
+ assert isinstance(ai_content, list)
+ assert isinstance(ai_content[0], dict)
+ self.assertEqual(ai_content[0], {"type": "text", "text": content_text})
+
+ if expected_command is not None:
+ self.assertEqual(len(result), 2)
+ provenance_message = result[1]
+ self.assertIsInstance(provenance_message, HumanMessage)
+ provenance_content = provenance_message.content
+ assert isinstance(provenance_content, list)
+ assert isinstance(provenance_content[0], dict)
+ provenance_text = provenance_content[0]["text"]
+ self.assertIn(f"/{expected_command} slash command", provenance_text)
+ self.assertIn("deterministic PostHog code", provenance_text)
+ else:
+ self.assertEqual(len(result), 1)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 973204ab2f12..837a811a19cf 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2585,6 +2585,10 @@
"form": {
"$ref": "#/definitions/AssistantForm"
},
+ "source": {
+ "description": "Provenance for non-LLM-authored messages. Format: `slash_command:<name>`.",
+ "type": "string"
+ },
"thinking": {
"description": "Thinking blocks, as well as server_tool_use and web_search_tool_result ones. Anthropic format of blocks.",
"items": {
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index b1fd67289cb7..02c97a8f17a6 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -195,6 +195,8 @@ export interface AssistantMessageMetadata {
form?: AssistantForm
/** Thinking blocks, as well as server_tool_use and web_search_tool_result ones. Anthropic format of blocks. */
thinking?: Record<string, unknown>[]
+ /** Provenance for non-LLM-authored messages. Format: `slash_command:<name>`. */
+ source?: string
}
export interface AssistantToolCall {
diff --git a/posthog/schema.py b/posthog/schema.py
index 3382b420b33e..1f1963454a89 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5984,6 +5984,10 @@ class AssistantMessageMetadata(BaseModel):
extra="forbid",
)
form: AssistantForm | None = None
+ source: str | None = Field(
+ default=None,
+ description=("Provenance for non-LLM-authored messages. Format: `slash_command:<name>`."),
+ )
thinking: list[dict[str, Any]] | None = Field(
default=None,
description=(