: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(phai): give the conversation summarizer a cacheable fixed prefix (#89896)
Carlos Marchalef416fe1082d
diff --git a/ee/hogai/utils/conversation_summarizer/prompts.py b/ee/hogai/utils/conversation_summarizer/prompts.pyindex a81cb7d1096a..5638d83de69f 100644--- a/ee/hogai/utils/conversation_summarizer/prompts.py+++ b/ee/hogai/utils/conversation_summarizer/prompts.py@@ -3,7 +3,7 @@ You are PostHog AI, the friendly and knowledgeable AI agent of PostHog.You are tasked with summarizing conversations.""".strip()-USER_PROMPT = """+SUMMARIZATION_INSTRUCTION_PROMPT = """Create a comprehensive summary of the conversation to date, ensuring you capture the user’s specific requests and your prior responses.This summary should be thorough in capturing research concepts, key insights, and relevant data that would be essential for continuing product management work without losing context.@@ -78,3 +78,7 @@ Please provide a comprehensive, accurate summary of the conversation so far foll**CRITICAL**: keep important details""".strip()++FINAL_TURN_PROMPT = """+Summarize the conversation above, following the structure in your instructions.+""".strip()diff --git a/ee/hogai/utils/conversation_summarizer/summarizer.py b/ee/hogai/utils/conversation_summarizer/summarizer.pyindex c0cdca8cf8f3..3d727d5274e3 100644--- a/ee/hogai/utils/conversation_summarizer/summarizer.py+++ b/ee/hogai/utils/conversation_summarizer/summarizer.py@@ -3,15 +3,16 @@ import datetimefrom abc import abstractmethodfrom collections.abc import Sequence-from langchain_core.messages import BaseMessage+from langchain_core.messages import BaseMessage, SystemMessagefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import ChatPromptTemplatefrom posthog.models import Team, Userfrom ee.hogai.llm import MaxChatAnthropic+from ee.hogai.utils.anthropic import add_cache_control-from .prompts import SYSTEM_PROMPT, USER_PROMPT+from .prompts import FINAL_TURN_PROMPT, SUMMARIZATION_INSTRUCTION_PROMPT, SYSTEM_PROMPTclass ConversationSummarizer:@@ -31,12 +32,22 @@ class ConversationSummarizer:def _get_model(self): ...def _construct_messages(self, messages: Sequence[BaseMessage]):+ # The summarization instruction carries no per-conversation data, so it leads the prompt to+ # keep the fixed prefix contiguous and identical between calls. Everything that changes per+ # call follows it: the project context `MaxChatMixin` appends to the system block, then the+ # conversation itself.return (- ChatPromptTemplate.from_messages([("system", SYSTEM_PROMPT)])+ ChatPromptTemplate.from_messages([self._construct_system_message()])+ messages- + ChatPromptTemplate.from_messages([("user", USER_PROMPT)])+ # The conversation can end with an assistant message, which the Anthropic API rejects as+ # a prefill. This turn keeps the request ending on a user message, and repeats the task+ # after a conversation that can reach the full 400k-token window.+ + ChatPromptTemplate.from_messages([("user", FINAL_TURN_PROMPT)]))+ def _construct_system_message(self) -> BaseMessage:+ return SystemMessage(content=f"{SYSTEM_PROMPT}\n\n{SUMMARIZATION_INSTRUCTION_PROMPT}")+def _parse_xml_tags(self, message: str) -> str:"""Extract analysis and summary tags from a message.@@ -80,8 +91,17 @@ class AnthropicConversationSummarizer(ConversationSummarizer):billable=True,)+ def _construct_system_message(self) -> BaseMessage:+ # The 1h TTL outlives the 5m one between compactions, which are minutes to hours apart.+ return add_cache_control(super()._construct_system_message(), ttl="1h")+def _construct_messages(self, messages: Sequence[BaseMessage]):- """Removes cache_control headers."""+ """Removes cache_control headers, so the only breakpoint is the one on the fixed prefix.++ The agent marks the last message of the conversation it hands over, which would make+ Anthropic write a cache entry for a ~400k-token prefix that no later call can read, because+ each compaction sends a conversation only it has.+ """messages_without_cache: list[BaseMessage] = []for message in messages:if isinstance(message.content, list):diff --git a/ee/hogai/utils/conversation_summarizer/test/test_nodes.py b/ee/hogai/utils/conversation_summarizer/test/test_nodes.pyindex db90e56b05ab..8a21c558be19 100644--- a/ee/hogai/utils/conversation_summarizer/test/test_nodes.py+++ b/ee/hogai/utils/conversation_summarizer/test/test_nodes.py@@ -9,6 +9,7 @@ from langchain_core.messages import (from parameterized import parameterizedfrom ee.hogai.utils.conversation_summarizer import AnthropicConversationSummarizer+from ee.hogai.utils.conversation_summarizer.prompts import SUMMARIZATION_INSTRUCTION_PROMPTclass TestAnthropicConversationSummarizer(BaseTest):@@ -175,3 +176,34 @@ class TestAnthropicConversationSummarizer(BaseTest):result = self.summarizer._construct_messages([])# Should return prompt template with just system and user promptsself.assertEqual(len(result.messages), 2)++ def test_only_cache_breakpoint_is_the_fixed_prefix(self):+ messages = self.summarizer._construct_messages(+ [+ LangchainHumanMessage(content=[{"type": "text", "text": "Hello"}]),+ LangchainAIMessage(content=[{"type": "text", "text": "Hi", "cache_control": {"type": "ephemeral"}}]),+ ]+ ).format_messages()++ cached = [+ (message, block)+ for message in messages+ for block in (message.content if isinstance(message.content, list) else [])+ if isinstance(block, dict) and "cache_control" in block+ ]+ self.assertEqual(len(cached), 1)+ cached_message, cached_block = cached[0]+ self.assertIs(cached_message, messages[0])+ self.assertIn(SUMMARIZATION_INSTRUCTION_PROMPT, cached_block["text"])+ self.assertEqual(cached_block["cache_control"], {"type": "ephemeral", "ttl": "1h"})++ @parameterized.expand(+ [+ ("conversation_ends_with_assistant_message", LangchainAIMessage(content="Done")),+ ("conversation_ends_with_human_message", LangchainHumanMessage(content="Thanks")),+ ]+ )+ def test_request_ends_on_a_user_turn(self, name, last_message):+ messages = self.summarizer._construct_messages([last_message]).format_messages()++ self.assertIsInstance(messages[-1], LangchainHumanMessage)