: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
feat(max): voice-mode prompt instruction when hands-free is active (#59590)
Paul D'Ambra66b33ac3cab2
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.pyindex dff84809c66a..df4a9ed06fc8 100644--- a/ee/hogai/context/context.py+++ b/ee/hogai/context/context.py@@ -447,14 +447,51 @@ class AssistantContextManager(AssistantContextMixin):async def _get_context_messages(self, state: BaseStateWithMessages) -> list[ContextMessage]:prompts: list[ContextMessage] = []+ ui_context = self.get_ui_context(state)if mode_prompt := self._get_mode_context_messages(state):prompts.append(mode_prompt)if contextual_tools := await self._get_contextual_tools_prompt():prompts.append(ContextMessage(content=contextual_tools, id=str(uuid4())))- if ui_context := await self._format_ui_context(self.get_ui_context(state)):- prompts.append(ContextMessage(content=ui_context, id=str(uuid4())))+ if voice_prompt := self._get_voice_mode_prompt(ui_context):+ prompts.append(ContextMessage(content=voice_prompt, id=str(uuid4())))+ if formatted_ui_context := await self._format_ui_context(ui_context):+ prompts.append(ContextMessage(content=formatted_ui_context, id=str(uuid4())))return self._deduplicate_context_messages(state, prompts)+ def _get_voice_mode_prompt(self, ui_context: MaxUIContext | None) -> str | None:+ """Return a voice-mode instruction reflecting the current turn's modality.++ Emits a tag whenever the frontend tells us explicitly whether voice mode is on+ or off — both states need to survive in conversation history so a typed turn+ that follows a spoken one cleanly overrides the earlier voice formatting rules+ (otherwise the prior <voice_mode> instruction keeps steering the model toward+ spelled-out numbers and no markdown).+ """+ if ui_context is None or ui_context.voice_mode is None:+ return None+ if ui_context.voice_mode:+ return (+ "<voice_mode>\n"+ "The user is asking via hands-free voice mode. Your response will be read "+ "aloud by text-to-speech. Write it so it sounds natural when spoken:\n"+ "- Spell out all numbers and currencies in words "+ '(e.g. "one hundred dollars from five thousand two hundred and thirty eight users", '+ 'not "$100 from 5,238 users").\n'+ "- Spell out percentages as words "+ '(e.g. "twelve point five percent", not "12.5%").\n'+ "- No markdown — no headings, no bullets, no bold, no inline code or code blocks.\n"+ "- No emoji.\n"+ "- Use plain sentences. Keep it concise — assume the user can't see the screen.\n"+ "</voice_mode>"+ )+ return (+ "<voice_mode>\n"+ "The user is no longer in hands-free voice mode for this turn. Ignore any "+ "earlier voice-mode formatting instructions in this conversation: you may use "+ "markdown, numerals, currency symbols, code blocks, and emoji as normal.\n"+ "</voice_mode>"+ )+async def _get_contextual_tools_prompt(self) -> str | None:from ee.hogai.registry import get_contextual_tool_classdiff --git a/ee/hogai/context/test/test_context.py b/ee/hogai/context/test/test_context.pyindex 9399be0c2e1a..28fa741f706c 100644--- a/ee/hogai/context/test/test_context.py+++ b/ee/hogai/context/test/test_context.py@@ -328,6 +328,29 @@ class TestAssistantContextManager(BaseTest):self.assertIsNone(result)mock_capture_exception.assert_called()+ def test_voice_mode_prompt_on_emits_speech_formatting_rules(self):+ prompt = self.context_manager._get_voice_mode_prompt(MaxUIContext(voice_mode=True))+ assert prompt is not None+ assert "<voice_mode>" in prompt+ assert "spelled out" in prompt.lower() or "spell out" in prompt.lower()++ def test_voice_mode_prompt_off_emits_explicit_override(self):+ # Explicit False must emit a counter-instruction so a typed turn after a spoken+ # turn isn't still steered by the earlier <voice_mode> prompt sitting in history.+ prompt = self.context_manager._get_voice_mode_prompt(MaxUIContext(voice_mode=False))+ assert prompt is not None+ assert "<voice_mode>" in prompt+ assert "no longer" in prompt.lower() or "ignore" in prompt.lower()++ @parameterized.expand(+ [+ ("voice_mode field absent", MaxUIContext(insights=None)),+ ("ui_context absent", None),+ ]+ )+ def test_voice_mode_prompt_absent_when_field_not_set(self, _name: str, ui_context: MaxUIContext | None):+ assert self.context_manager._get_voice_mode_prompt(ui_context) is None+def test_deduplicate_context_messages(self):"""Test that context messages are deduplicated based on existing context message content"""# Create state with existing context messagesdiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 430cd277b2fb..d4ce801a7572 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -25933,6 +25933,9 @@"$ref": "#/definitions/MaxNotebookContext"},"type": "array"+ },+ "voice_mode": {+ "type": "boolean"}},"type": "object"diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 5cc23c2a5151..a4354d44ed9a 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -1002,9 +1002,16 @@ export const maxThreadLogic = kea<maxThreadLogicType>([return}const contextualTools = Object.fromEntries(values.tools.map((tool) => [tool.identifier, tool.context]))- const mergedUiContext = uiContext- ? { ...values.compiledContext, ...uiContext }- : values.compiledContext || undefined+ // Always send voice_mode as an explicit boolean when handsFreeLogic is mounted,+ // not just when active. Otherwise a typed turn following a spoken one inherits+ // the earlier <voice_mode> system instruction from conversation history and+ // keeps formatting for speech (no markdown, spelled-out numbers).+ const handsFree = handsFreeLogic.findMounted({ tabId: props.tabId })+ const voiceMode = handsFree ? { voice_mode: handsFree.values.isActive } : undefined+ const mergedUiContext =+ uiContext || voiceMode+ ? { ...values.compiledContext, ...uiContext, ...voiceMode }+ : values.compiledContext || undefinedconst billingContext =values.billingContext && values.featureFlags[FEATURE_FLAGS.MAX_BILLING_CONTEXT]? values.billingContextdiff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.tsindex b349eef31484..b47d5b7e820c 100644--- a/frontend/src/scenes/max/maxTypes.ts+++ b/frontend/src/scenes/max/maxTypes.ts@@ -85,6 +85,10 @@ export interface MaxUIContext {evaluations?: MaxEvaluationContext[]notebooks?: MaxNotebookContext[]form_answers?: Record<string, string> // question_id -> answer for create_form tool responses+ // Request modality: true when the user is asking via hands-free voice mode. Backend+ // appends a voice-formatting instruction to the prompt so the response is suitable+ // for TTS (numbers spelled out, no markdown, etc).+ voice_mode?: boolean}// Taxonomic filter optionsdiff --git a/posthog/schema.py b/posthog/schema.pyindex 5a5874a178d7..a1b57f4dffd2 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -23643,6 +23643,7 @@ class MaxUIContext(BaseModel):form_answers: dict[str, str] | None = Noneinsights: list[MaxInsightContext] | None = Nonenotebooks: list[MaxNotebookContext] | None = None+ voice_mode: bool | None = Noneclass QueryRequest(BaseModel):