: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(replay-vision): add posthog ai chat for guiding users for prompts (#61895)
Hayne Ryu488c925a0b96
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 8143d16e99a4..729a6d745a61 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -3859,7 +3859,8 @@"marketing_audit_utm","marketing_suggest_conversion_goals","marketing_suggest_utm_mappings",- "summarize_replay_vision_summaries"+ "summarize_replay_vision_summaries",+ "draft_replay_vision_scanner_prompt"],"type": "string"},diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex f5bd8e4ce9f4..158103759396 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -515,6 +515,7 @@ export type AssistantTool =| 'marketing_suggest_conversion_goals'| 'marketing_suggest_utm_mappings'| 'summarize_replay_vision_summaries'+ | 'draft_replay_vision_scanner_prompt'export enum AgentMode {ProductAnalytics = 'product_analytics',diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 3b72a7958ad7..53b334d4b22e 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -685,6 +685,18 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {return 'Summarizing session summaries...'},},+ draft_replay_vision_scanner_prompt: {+ name: 'Write scanner prompts',+ description: 'Write scanner prompts for Replay Vision scanners',+ icon: iconForType('session_replay'),+ modes: [AgentMode.SessionReplay],+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Drafted scanner prompt'+ }+ return 'Drafting scanner prompt...'+ },+ },create_survey: {name: 'Create surveys',description: 'Create surveys in seconds',diff --git a/posthog/schema.py b/posthog/schema.pyindex bc9ce1710330..321987d6d6e6 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -808,6 +808,7 @@ class AssistantTool(StrEnum):MARKETING_SUGGEST_CONVERSION_GOALS = "marketing_suggest_conversion_goals"MARKETING_SUGGEST_UTM_MAPPINGS = "marketing_suggest_utm_mappings"SUMMARIZE_REPLAY_VISION_SUMMARIES = "summarize_replay_vision_summaries"+ DRAFT_REPLAY_VISION_SCANNER_PROMPT = "draft_replay_vision_scanner_prompt"class AssistantToolCall(BaseModel):diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex 628b62a681b9..ca35c1420d66 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -21,6 +21,34 @@ MAX_SUMMARIES = 100# Inline citation markers the model emits in summary text; stripped before handing to Max as noise._EVENT_ID_CITATION_RE = re.compile(r"\(event_id [0-9a-f]{16}\)", re.IGNORECASE)+DRAFT_PROMPT_TOOL_DESCRIPTION = dedent("""+ Use this tool to write or improve the instruction prompt for the Replay Vision scanner the user is+ currently configuring, then fill it into their configuration form.++ # When to use+ - The user is configuring a scanner and asks for help writing, drafting, or improving its prompt+ - The user describes what they want a scanner to detect, summarize, classify, or score and wants that turned into a good prompt++ # How to write a good scanner prompt+ A scanner prompt is the instruction the model follows while watching a single session recording.+ Write it as a direct, specific instruction grounded in observable behavior. The shape depends on the scanner type:+ - monitor: a yes/no question about whether something happened (e.g. "Did the user fail to complete checkout?").+ State what counts as a yes, and ask for a one-sentence reason.+ - classifier: an instruction to categorize the session along one dimension (e.g. by primary user intent).+ Describe the dimension; the tag vocabulary is configured separately, so don't list tags in the prompt.+ - scorer: an instruction to rate the session on a single dimension (e.g. frustration).+ Describe what a low score versus a high score means; the numeric scale is configured separately.+ - summarizer: an instruction for what the summary should focus on (e.g. the user's goal and the obstacles they hit).++ Keep it concrete. Avoid vague adjectives, multi-part questions, and references to data the model cannot+ observe in a recording (e.g. revenue, account tier).++ # After drafting+ Call this tool with the finished prompt — it fills the prompt field in the form the user is editing.+ Then briefly explain the choices you made so the user can refine them.+ """).strip()++SUMMARIZE_SUMMARIES_TOOL_DESCRIPTION = dedent("""Use this tool to reason across the per-session summaries produced by a Replay Vision *summarizer* scanner.@@ -35,6 +63,51 @@ SUMMARIZE_SUMMARIES_TOOL_DESCRIPTION = dedent("""""").strip()+VALID_SCANNER_TYPES = {t.value for t in ScannerType}+++class DraftScannerPromptArgs(BaseModel):+ prompt: str = Field(description="The finished scanner instruction prompt to fill into the configuration form.")+ scanner_type: str | None = Field(+ default=None,+ description="The scanner type the prompt is for (monitor, classifier, scorer, or summarizer). "+ "Only required when not already available from context.",+ )+++class DraftReplayVisionScannerPromptTool(MaxTool):+ name: str = "draft_replay_vision_scanner_prompt"+ description: str = DRAFT_PROMPT_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = DraftScannerPromptArgs+ context_prompt_template: str = (+ "The user is editing the configuration for a Replay Vision {scanner_type} scanner. "+ "Its current prompt is:\n{current_prompt}"+ )++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ # Drafting writes into the scanner's configuration form, which requires editor access.+ return [("session_recording", "editor")]++ async def _arun_impl(self, prompt: str, scanner_type: str | None = None) -> tuple[str, dict[str, Any]]:+ if not await self._is_enabled():+ return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}++ cleaned = prompt.strip()+ if not cleaned:+ return "No prompt to apply. Please provide the drafted prompt text.", {"error": "empty_prompt"}++ resolved_type = scanner_type or self.context.get("scanner_type")+ # Artifact is consumed by the frontend callback, which fills the prompt field in the form.+ return "Drafted a scanner prompt and filled it into the configuration form.", {+ "prompt": cleaned,+ "scanner_type": resolved_type if resolved_type in VALID_SCANNER_TYPES else None,+ }++ @database_sync_to_async+ def _is_enabled(self) -> bool:+ return is_replay_vision_enabled(self._user, self._team)++class SummarizeSummariesArgs(BaseModel):scanner_id: str | None = Field(default=None,diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.pynew file mode 100644index 000000000000..1707670c8684--- /dev/null+++ b/products/replay_vision/backend/tests/test_max_tools.py@@ -0,0 +1,67 @@+import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from langchain_core.runnables import RunnableConfig+from parameterized import parameterized++from products.replay_vision.backend.max_tools import DraftReplayVisionScannerPromptTool++_FLAG_PATH = "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled"+++class TestDraftReplayVisionScannerPromptTool(BaseTest):+ def _tool(self, context: dict | None = None) -> DraftReplayVisionScannerPromptTool:+ configurable: dict = {"team": self.team, "user": self.user}+ if context is not None:+ configurable["contextual_tools"] = {"draft_replay_vision_scanner_prompt": context}+ config: RunnableConfig = {"configurable": configurable}+ return DraftReplayVisionScannerPromptTool(team=self.team, user=self.user, config=config)++ @parameterized.expand(+ [+ ("monitor", "monitor"),+ ("classifier", "classifier"),+ ("scorer", "scorer"),+ ("summarizer", "summarizer"),+ ("unknown_type", None),+ ]+ )+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_fills_prompt_and_resolves_type(self, scanner_type, expected_type):+ with patch(_FLAG_PATH, return_value=True):+ content, artifact = await self._tool()._arun_impl(+ prompt=" Did checkout fail? ", scanner_type=scanner_type+ )++ assert "filled it into the configuration form" in content+ assert artifact["prompt"] == "Did checkout fail?"+ assert artifact["scanner_type"] == expected_type++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_resolves_scanner_type_from_context(self):+ with patch(_FLAG_PATH, return_value=True):+ _, artifact = await self._tool(context={"scanner_type": "scorer"})._arun_impl(prompt="Rate frustration.")++ assert artifact["scanner_type"] == "scorer"++ @parameterized.expand([("", "empty_prompt"), (" ", "empty_prompt")])+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_rejects_empty_prompt(self, prompt, expected_error):+ with patch(_FLAG_PATH, return_value=True):+ content, artifact = await self._tool()._arun_impl(prompt=prompt)++ assert artifact["error"] == expected_error+ assert "prompt" not in artifact++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_gated_off_when_product_disabled(self):+ with patch(_FLAG_PATH, return_value=False):+ content, artifact = await self._tool()._arun_impl(prompt="Did checkout fail?")++ assert artifact["error"] == "not_enabled"+ assert "not enabled" in contentdiff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsxindex f7600cf42978..0ab5fde2081b 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx@@ -1,12 +1,17 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'+import { useCallback } from 'react'-import { LemonInput, LemonSegmentedButton, LemonSwitch, LemonTextArea } from '@posthog/lemon-ui'+import { IconAI } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSegmentedButton, LemonSwitch, LemonTextArea } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { useMaxTool } from 'scenes/max/useMaxTool'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { replayScannerLogic } from '../replayScannerLogic'-import { SummarizerScannerConfig } from '../types'+import { SummarizerScannerConfig, scannerTypeLabel } from '../types'const SUMMARIZER_LENGTH_OPTIONS: { value: SummarizerScannerConfig['length']; label: string }[] = [{ value: 'short', label: 'Short (1-2 sentences)' },@@ -14,6 +19,58 @@ const SUMMARIZER_LENGTH_OPTIONS: { value: SummarizerScannerConfig['length']; lab{ value: 'long', label: 'Long (3-5 paragraphs)' },]+/** Prompt field with a Max entry point that drafts the prompt and fills it back into the form. */+function ScannerPromptField({ scannerId, placeholder }: { scannerId: string; placeholder: string }): JSX.Element {+ const logic = replayScannerLogic({ id: scannerId })+ const { scanner } = useValues(logic)+ const { setScannerValue } = useActions(logic)++ const onDraftedPrompt = useCallback(+ (toolOutput: { prompt?: string; error?: string }) => {+ if (!toolOutput?.error && toolOutput?.prompt) {+ setScannerValue(['scanner_config', 'prompt'], toolOutput.prompt)+ }+ },+ [setScannerValue]+ )++ const { openMax } = useMaxTool({+ identifier: 'draft_replay_vision_scanner_prompt',+ active: !!scanner,+ context: {+ scanner_type: scanner?.scanner_type,+ current_prompt: scanner?.scanner_config?.prompt || '',+ },+ contextDescription: scanner+ ? { text: `${scannerTypeLabel(scanner.scanner_type)} scanner`, icon: iconForType('session_replay') }+ : undefined,+ initialMaxPrompt: 'Help me write the prompt for this scanner',+ callback: onDraftedPrompt,+ })++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <label className="text-sm font-medium">Prompt</label>+ {openMax && (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconAI />}+ onClick={() => openMax()}+ data-attr="replay-vision-write-prompt-with-ai"+ >+ Write with PostHog AI+ </LemonButton>+ )}+ </div>+ <LemonField name="scanner_config.prompt">+ <LemonTextArea placeholder={placeholder} minRows={6} />+ </LemonField>+ </div>+ )+}+export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): JSX.Element {const { scanner } = useValues(replayScannerLogic({ id: scannerId }))@@ -24,12 +81,10 @@ export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): Jif (scanner.scanner_type === 'summarizer') {return (<div className="space-y-4">- <LemonField name="scanner_config.prompt" label="Prompt">- <LemonTextArea- placeholder="Summarize what the user did, focusing on their goal and any obstacles they hit."- minRows={6}- />- </LemonField>+ <ScannerPromptField+ scannerId={scannerId}+ placeholder="Summarize what the user did, focusing on their goal and any obstacles they hit."+ /><LemonField name="scanner_config.length" label="Summary length"><LemonSegmentedButton options={SUMMARIZER_LENGTH_OPTIONS} /></LemonField>@@ -40,12 +95,10 @@ export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): Jif (scanner.scanner_type === 'monitor') {return (<div className="space-y-4">- <LemonField name="scanner_config.prompt" label="Prompt">- <LemonTextArea- placeholder="Did the user encounter a payment failure? Answer yes or no with a one-sentence reason."- minRows={6}- />- </LemonField>+ <ScannerPromptField+ scannerId={scannerId}+ placeholder="Did the user encounter a payment failure? Answer yes or no with a one-sentence reason."+ /><LemonField name="scanner_config.allow_inconclusive">{({ value, onChange }) => (<div className="flex items-center gap-2">@@ -67,9 +120,10 @@ export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): Jif (scanner.scanner_type === 'classifier') {return (<div className="space-y-4">- <LemonField name="scanner_config.prompt" label="Prompt">- <LemonTextArea placeholder="Categorize this session by its primary user intent." minRows={6} />- </LemonField>+ <ScannerPromptField+ scannerId={scannerId}+ placeholder="Categorize this session by its primary user intent."+ /><LemonField name="scanner_config.tags" label="Tag vocabulary">{({ value, onChange }) => (<LemonInputSelect@@ -115,12 +169,10 @@ export function ScannerTypeConfigEditor({ scannerId }: { scannerId: string }): Jif (scanner.scanner_type === 'scorer') {return (<div className="space-y-4">- <LemonField name="scanner_config.prompt" label="Prompt">- <LemonTextArea- placeholder="Rate how frustrated the user appeared during this session."- minRows={6}- />- </LemonField>+ <ScannerPromptField+ scannerId={scannerId}+ placeholder="Rate how frustrated the user appeared during this session."+ /><LemonField name="scanner_config.scale">{({ value, onChange, error }) => {const scale = (value as { min: number; max: number; label?: string }) ?? { min: 0, max: 10 }