: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(max): Compact at 400k w/ Sonnet instead of 100k w/ Haiku (#74590)
Michael Matloka3040bd012fdf
diff --git a/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py b/ee/hogai/chat_agent/slash_commands/commands/ticket/command.pyindex b3362d5f5770..6c05d2a031f8 100644--- a/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py+++ b/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py@@ -107,13 +107,18 @@ class TicketCommand(SlashCommand):def _get_model(self) -> MaxChatAnthropic:# We are not billing for conversation summary since we would be billing per-ticket creation.+ # Needs a 1M-context model because this summarizes the whole conversation window, which can+ # hold up to CONVERSATION_WINDOW_SIZE tokens.return MaxChatAnthropic(- model="claude-haiku-4-5",+ model="claude-sonnet-5",streaming=True,stream_usage=True,user=self._user,team=self._team,max_tokens=2048,+ # Sonnet 5 thinks by default and `max_tokens` covers thinking plus response together,+ # so leaving it on would let thinking eat the summary's budget.+ thinking={"type": "disabled"},billable=False,)diff --git a/ee/hogai/chat_agent/test/test_chat_agent.py b/ee/hogai/chat_agent/test/test_chat_agent.pyindex 0698dfa981fc..aa68895a454a 100644--- a/ee/hogai/chat_agent/test/test_chat_agent.py+++ b/ee/hogai/chat_agent/test/test_chat_agent.py@@ -1706,7 +1706,7 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):),])- mock_tool.return_value = ("Event list" * 128000, None)+ mock_tool.return_value = ("Event list" * 200000, None)mock_should_compact.side_effect = cycle([False, True]) # Also changed thisgraph = (@@ -1726,7 +1726,7 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):tool_calls=[{"id": "1", "name": "read_taxonomy", "args": {"query": {"kind": "events"}}}],),),- ("message", AssistantToolCallMessage(tool_call_id="1", content="Event list" * 128000)),+ ("message", AssistantToolCallMessage(tool_call_id="1", content="Event list" * 200000)),("message", HumanMessage(content="First")), # Should copy this message("message", AssistantMessage(content="After summary")),]diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex 9ef6abf0ddae..5063a15d8e37 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -59,7 +59,7 @@ from .prompts import (NOTEBOOK_MARKDOWN_MAX_LENGTH = 100_000# A dashboard's executed-results context is bounded so it can't overflow the conversation window-# (compaction_manager.CONVERSATION_WINDOW_SIZE = 100k). If it overflows, the whole conversation —+# (compaction_manager.CONVERSATION_WINDOW_SIZE). If it overflows, the whole conversation —# including this dashboard — gets summarized down to a few thousand tokens, so Max loses the# dashboard it was just asked about. Over budget, we fall back to schema-only (insight names +# queries, no result tables), which still lets Max identify and describe the dashboard and fetchdiff --git a/ee/hogai/core/agent_modes/compaction_manager.py b/ee/hogai/core/agent_modes/compaction_manager.pyindex e5b4008a55ef..66685924c877 100644--- a/ee/hogai/core/agent_modes/compaction_manager.py+++ b/ee/hogai/core/agent_modes/compaction_manager.py@@ -49,9 +49,14 @@ class ConversationCompactionManager(ABC):Manages conversation window boundaries, message filtering, and summarization decisions."""- CONVERSATION_WINDOW_SIZE = 100_000+ CONVERSATION_WINDOW_SIZE = 400_000"""Determines the maximum number of tokens allowed in the conversation window.++ Compaction blocks the user's turn for the length of a full summarization call, so this is set+ well below the 1M context both the root model and the summarizer support: the cost of carrying+ a larger window on every turn is mostly cache reads, while the cost of compacting is dead time+ the user watches. Raising this trades per-turn input tokens for far fewer compactions."""APPROXIMATE_TOKEN_LENGTH = 4"""diff --git a/ee/hogai/core/agent_modes/executables.py b/ee/hogai/core/agent_modes/executables.pyindex 8837c1b5cfce..c947993ab33d 100644--- a/ee/hogai/core/agent_modes/executables.py+++ b/ee/hogai/core/agent_modes/executables.py@@ -161,7 +161,7 @@ class AgentExecutable(BaseAgentLoopRootExecutable):summary = await AnthropicConversationSummarizer(self._team,self._user,- extend_context_window=current_token_count > 195_000,+ conversation_start_dt=state.start_dt,).summarize(messages_to_summarize)summary_message = ContextMessage(@@ -271,17 +271,11 @@ class AgentExecutable(BaseAgentLoopRootExecutable):}def _get_model(self, state: AssistantState, tools: list["MaxTool"]):- model_name = "claude-sonnet-4-6"- if self._has_legacy_summarize_sessions_messages(state.messages):- model_name = "claude-sonnet-4-5"-- is_sonnet_4_5 = model_name == "claude-sonnet-4-5"-gateway_kwargs = self._get_gateway_kwargs()is_routing_through_llm_gateway = bool(gateway_kwargs)base_model = MaxChatAnthropic(- model=model_name,+ model="claude-sonnet-4-6",streaming=True,stream_usage=True,user=self._user,@@ -290,11 +284,11 @@ class AgentExecutable(BaseAgentLoopRootExecutable):"interleaved-thinking-2025-05-14","fine-grained-tool-streaming-2025-05-14",],- max_tokens=8192 if is_sonnet_4_5 else 16384,- thinking=self.THINKING_CONFIG if not is_sonnet_4_5 else {"type": "enabled", "budget_tokens": 1024},+ max_tokens=16384,+ thinking=self.THINKING_CONFIG,# langchain-anthropic 0.3.x doesn't have a first-class effort field;# forward it via model_kwargs so the Anthropic API receives output_config.- model_kwargs={"output_config": {"effort": "medium"}} if not is_sonnet_4_5 else {},+ model_kwargs={"output_config": {"effort": "medium"}},conversation_start_dt=state.start_dt,billable=True,bypass_proxy=is_routing_through_llm_gateway,@@ -384,28 +378,6 @@ class AgentExecutable(BaseAgentLoopRootExecutable):"""Process the output message."""return normalize_ai_message(message)- @staticmethod- def _has_legacy_summarize_sessions_messages(messages: Sequence[AssistantMessageUnion]) -> bool:- """Detect pre-migration summarize_sessions AssistantMessages with meta.form.-- Before the migration, summarize_sessions returned a ToolMessagesArtifact containing- an AssistantMessage with meta.form (the "Open report" button). This AssistantMessage- converts to a trailing AIMessage, causing a prefill error with Sonnet 4.6.- Sonnet 4.5 handles this gracefully, so we fall back to it for legacy conversations.- """- for message in messages:- if (- isinstance(message, AssistantMessage)- and message.meta- and message.meta.form- and any(- option.href and option.href.startswith("/session-summaries/")- for option in message.meta.form.options- )- ):- return True- return False-class AgentToolsExecutable(BaseAgentLoopExecutable):async def arun(self, state: AssistantState, config: RunnableConfig) -> PartialAssistantState:diff --git a/ee/hogai/core/agent_modes/test/test_compaction_manager.py b/ee/hogai/core/agent_modes/test/test_compaction_manager.pyindex f139c0d79894..0af19c5ceca9 100644--- a/ee/hogai/core/agent_modes/test/test_compaction_manager.py+++ b/ee/hogai/core/agent_modes/test/test_compaction_manager.py@@ -122,11 +122,11 @@ class TestAnthropicConversationCompactionManager(BaseTest):@parameterized.expand([# (num_human_messages, token_count, should_compact)- [1, 90000, False], # Only 1 human message, under limit- [2, 90000, False], # Only 2 human messages, under limit- [3, 80000, False], # 3 human messages but under token limit- [3, 110000, True], # 3 human messages and over token limit- [5, 110000, True], # Many messages over limit+ [1, 390000, False], # Only 1 human message, under limit+ [2, 390000, False], # Only 2 human messages, under limit+ [3, 380000, False], # 3 human messages but under token limit+ [3, 410000, True], # 3 human messages and over token limit+ [5, 410000, True], # Many messages over limit])async def test_should_compact_conversation(self, num_human_messages, token_count, should_compact):@@ -163,23 +163,23 @@ class TestAnthropicConversationCompactionManager(BaseTest):# With 2 human messages, should use estimation and not call _get_token_countresult = await self.window_manager.should_compact_conversation(mock_model, messages, tools=tools)- # Total should be well under 100k limit+ # Total should be well under the window limitself.assertFalse(result)async def test_should_compact_conversation_with_tools_over_limit(self):"""Test that tools push estimation over limit with 2 or fewer human messages"""+ # Together these sit just under CONVERSATION_WINDOW_SIZE, so only the tool schemas can tip+ # the estimate over it.messages: list[BaseMessage] = [- LangchainHumanMessage(content="A" * 200000), # ~50k tokens- LangchainAIMessage(content="B" * 200000), # ~50k tokens+ LangchainHumanMessage(content="A" * 780000), # ~195k tokens+ LangchainAIMessage(content="B" * 780000), # ~195k tokens]- # Create large tool schemas to push over 100k limittools = [{"type": "function", "function": {"name": f"tool_{i}", "description": "X" * 1000}} for i in range(100)]mock_model = MagicMock()result = await self.window_manager.should_compact_conversation(mock_model, messages, tools=tools)- # Should be over the 100k limitself.assertTrue(result)def test_get_estimated_assistant_message_tokens_human_message(self):diff --git a/ee/hogai/core/agent_modes/test/test_executables.py b/ee/hogai/core/agent_modes/test/test_executables.pyindex 289bbceaef7a..cfe848f4729b 100644--- a/ee/hogai/core/agent_modes/test/test_executables.py+++ b/ee/hogai/core/agent_modes/test/test_executables.py@@ -333,8 +333,8 @@ class TestAgentNode(ClickhouseTestMixin, BaseTest):@patch("ee.hogai.utils.conversation_summarizer.AnthropicConversationSummarizer.summarize")async def test_conversation_summarization_flow(self, mock_summarize, mock_calculate_tokens, mock_model):"""Test that conversation is summarized when it gets too long"""- # Return a token count higher than CONVERSATION_WINDOW_SIZE (100,000)- mock_calculate_tokens.return_value = 150_000+ # Return a token count higher than CONVERSATION_WINDOW_SIZE+ mock_calculate_tokens.return_value = 450_000mock_summarize.return_value = "This is a summary of the conversation so far."mock_model_instance = FakeChatOpenAI(responses=[LangchainAIMessage(content="Response after summary")])@@ -369,8 +369,8 @@ class TestAgentNode(ClickhouseTestMixin, BaseTest):@patch("ee.hogai.utils.conversation_summarizer.AnthropicConversationSummarizer.summarize")async def test_conversation_summarization_on_first_turn(self, mock_summarize, mock_calculate_tokens, mock_model):"""Test that on first turn, the last message is excluded from summarization"""- # Return a token count higher than CONVERSATION_WINDOW_SIZE (100,000)- mock_calculate_tokens.return_value = 150_000+ # Return a token count higher than CONVERSATION_WINDOW_SIZE+ mock_calculate_tokens.return_value = 450_000mock_summarize.return_value = "Summary without last message"mock_model_instance = FakeChatOpenAI(responses=[LangchainAIMessage(content="Response")])@@ -401,7 +401,7 @@ class TestAgentNode(ClickhouseTestMixin, BaseTest):self, mock_summarize, mock_calculate_tokens, mock_model):"""Test that mode reminder is inserted after summary when modes feature flag is enabled"""- mock_calculate_tokens.return_value = 150_000+ mock_calculate_tokens.return_value = 450_000mock_summarize.return_value = "Summary of conversation"mock_model_instance = FakeChatOpenAI(responses=[LangchainAIMessage(content="Response")])@@ -658,7 +658,7 @@ class TestAgentNode(ClickhouseTestMixin, BaseTest):from ee.hogai.utils.types.base import ReplaceMessages# Trigger summarization flow which returns ReplaceMessages- mock_calculate_tokens.return_value = 150_000+ mock_calculate_tokens.return_value = 450_000mock_summarize.return_value = "Conversation summary"mock_model.return_value = FakeChatOpenAI(responses=[LangchainAIMessage(content="Response")])diff --git a/ee/hogai/research_agent/executables.py b/ee/hogai/research_agent/executables.pyindex 6e6090c64d58..e32923719a68 100644--- a/ee/hogai/research_agent/executables.py+++ b/ee/hogai/research_agent/executables.py@@ -22,12 +22,12 @@ class ResearchAgentExecutable(PlanModeExecutable):THINKING_CONFIG = {"type": "enabled", "budget_tokens": 4096}MAX_TOKENS = 16_384- def _get_model(self, state: AssistantState, tools: list["MaxTool"]):- is_research_mode = state.supermode == AgentMode.RESEARCH- model_name = "claude-opus-4-6" if is_research_mode else "claude-sonnet-4-6"+ def _get_model_name(self, state: AssistantState) -> str:+ return "claude-opus-4-6" if state.supermode == AgentMode.RESEARCH else "claude-sonnet-4-6"+ def _get_model(self, state: AssistantState, tools: list["MaxTool"]):base_model = MaxChatAnthropic(- model=model_name,+ model=self._get_model_name(state),streaming=True,stream_usage=True,user=self._user,diff --git a/ee/hogai/utils/anthropic.py b/ee/hogai/utils/anthropic.pyindex 8c41db57cc9f..e62492532eb0 100644--- a/ee/hogai/utils/anthropic.py+++ b/ee/hogai/utils/anthropic.py@@ -128,4 +128,26 @@ def convert_to_anthropic_messages(history.extend(convert_to_anthropic_message(message, tool_result_map))except ValueError:continue- return history+ return drop_trailing_assistant_messages(history)+++def drop_trailing_assistant_messages(history: list[messages.BaseMessage]) -> list[messages.BaseMessage]:+ """Drop assistant messages the conversation ends on, so we never prefill.++ Anthropic reads a trailing assistant turn as content to continue from, which Sonnet 4.6 and+ later reject outright. A conversation can end on one when a tool appended its own assistant+ message after the tool result, which the pre-migration `summarize_sessions` did to render its+ "Open report" button.++ Assistant messages carrying tool calls are left in place: dropping one would orphan the tool+ result that follows it, which Anthropic rejects too.+ """+ end = len(history)+ while end > 0:+ message = history[end - 1]+ if not isinstance(message, messages.AIMessage) or message.tool_calls:+ break+ end -= 1+ # A history that is nothing but assistant messages has no valid prefix to send, so leave it+ # alone and let the caller's own validation report it.+ return history[:end] if end > 0 else historydiff --git a/ee/hogai/utils/conversation_summarizer/summarizer.py b/ee/hogai/utils/conversation_summarizer/summarizer.pyindex a85e17860249..c0cdca8cf8f3 100644--- a/ee/hogai/utils/conversation_summarizer/summarizer.py+++ b/ee/hogai/utils/conversation_summarizer/summarizer.py@@ -1,4 +1,5 @@import re+import datetimefrom abc import abstractmethodfrom collections.abc import Sequence@@ -14,9 +15,10 @@ from .prompts import SYSTEM_PROMPT, USER_PROMPTclass ConversationSummarizer:- def __init__(self, team: Team, user: User):+ def __init__(self, team: Team, user: User, conversation_start_dt: datetime.datetime | None = None):self._user = userself._team = team+ self._conversation_start_dt = conversation_start_dtasync def summarize(self, messages: Sequence[BaseMessage]) -> str:prompt = self._construct_messages(messages)@@ -56,18 +58,23 @@ class ConversationSummarizer:class AnthropicConversationSummarizer(ConversationSummarizer):- def __init__(self, team: Team, user: User, extend_context_window: bool | None = False):- super().__init__(team, user)- self._extend_context_window = extend_context_window-def _get_model(self):- # Haiku has 200k token limit. Sonnet has 1M token limit (GA on claude-sonnet-4-6).return MaxChatAnthropic(- model="claude-sonnet-4-6" if self._extend_context_window else "claude-haiku-4-5",+ # Sonnet 5 has a 1M token limit, so it can compact a conversation of any size we let+ # grow. Haiku's 200k limit no longer covers CONVERSATION_WINDOW_SIZE.+ model="claude-sonnet-5",streaming=False,stream_usage=False,- max_tokens=8192,+ max_tokens=16384,disable_streaming=True,+ # Sonnet 5 thinks by default, and `max_tokens` caps thinking plus response text+ # together. A thinking overrun here would truncate the summary, which silently drops+ # the conversation history it is supposed to preserve. The prompt already asks for an+ # explicit `<analysis>` pass before `<summary>`, so the reasoning happens either way.+ thinking={"type": "disabled"},+ # Without this, `MaxChatMixin._get_project_org_user_variables` stamps the current+ # wall-clock second into the injected context message.+ conversation_start_dt=self._conversation_start_dt,user=self._user,team=self._team,billable=True,diff --git a/ee/hogai/utils/test/test_anthropic.py b/ee/hogai/utils/test/test_anthropic.pyindex 9ce55c35b102..bc9d481f2bab 100644--- a/ee/hogai/utils/test/test_anthropic.py+++ b/ee/hogai/utils/test/test_anthropic.py@@ -1,13 +1,22 @@from posthog.test.base import BaseTest-from langchain_core.messages import HumanMessage+from langchain_core.messages import AIMessage, HumanMessagefrom parameterized import parameterized-from posthog.schema import AssistantMessage, AssistantMessageMetadata+from posthog.schema import (+ AssistantForm,+ AssistantFormOption,+ AssistantMessage,+ AssistantMessageMetadata,+ AssistantToolCall,+ AssistantToolCallMessage,+ HumanMessage as SchemaHumanMessage,+)from ee.hogai.utils.anthropic import (add_cache_control,convert_assistant_message_to_anthropic_message,+ convert_to_anthropic_messages,get_anthropic_thinking_from_assistant_message,)@@ -141,3 +150,49 @@ class TestAnthropicUtils(BaseTest):self.assertIn("deterministic PostHog code", provenance_text)else:self.assertEqual(len(result), 1)++ @parameterized.expand(+ [+ # Legacy summarize_sessions appended its "Open report" message after the tool result,+ # leaving the conversation on an assistant turn.+ ["legacy_form_message_last", True, 1],+ ["human_message_last", False, 3],+ ]+ )+ def test_conversation_never_ends_on_an_assistant_turn(self, _name, ends_with_assistant, expected_length):+ conversation: list = [+ SchemaHumanMessage(content="Summarize my sessions"),+ AssistantMessage(+ content="Report complete: Sessions summary",+ id="report",+ meta=AssistantMessageMetadata(+ form=AssistantForm(+ options=[AssistantFormOption(value="Open report", href="/session-summaries/abc")]+ )+ ),+ ),+ ]+ if not ends_with_assistant:+ conversation.append(SchemaHumanMessage(content="Thanks"))++ result = convert_to_anthropic_messages(conversation, {})++ self.assertEqual(len(result), expected_length)+ self.assertNotIsInstance(result[-1], AIMessage)++ def test_assistant_message_with_tool_calls_is_not_dropped(self):+ conversation: list = [+ SchemaHumanMessage(content="Run it"),+ AssistantMessage(+ content="Running",+ id="call",+ tool_calls=[AssistantToolCall(id="t1", name="read_data", args={})],+ ),+ ]+ tool_results = {"t1": AssistantToolCallMessage(content="done", tool_call_id="t1", id="result")}++ result = convert_to_anthropic_messages(conversation, tool_results)++ # The assistant turn stays because dropping it would orphan its tool result, which follows it.+ self.assertIsInstance(result[1], AIMessage)+ self.assertEqual(len(result), 3)