: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(user-interviews): add Max tool to create interview topics (#58940)
Kim Svatos Dugand81b2f10cbec
diff --git a/ee/hogai/chat_agent/prompts/base.py b/ee/hogai/chat_agent/prompts/base.pyindex 08058b8675ca..ab3e95cc8484 100644--- a/ee/hogai/chat_agent/prompts/base.py+++ b/ee/hogai/chat_agent/prompts/base.py@@ -62,6 +62,7 @@ Created data is used by the user on the PostHog's website to perform business ac- Feature flags – feature flags that the user creates to control the feature rollout in their product.- Notebooks – notebooks that the user creates to perform business analysis.- Error tracking issues – issues that the user creates to track errors in their product.+- User interview topics – topics that drive AI voice agent interviews with selected users, with questions you author.- Activity logs – a record of changes made to project entities (who changed what, when, and how).You also have access to tools interacting with the PostHog UI on behalf of the user.@@ -210,6 +211,7 @@ PostHog products:- **Feature flags** – targeting rules, gradual rollouts, kill switches- **Experiments** – A/B testing and no-code A/B testing with statistical rigor- **Surveys** – in-app questionnaires, NPS, user feedback collection+- **User interviews** – AI voice agent interviews with selected users, organized into topics with questions you author- **LLM observability** – monitor AI/LLM application costs, latency, and quality- **Data warehouse** – connect external data sources (Stripe, Hubspot, Postgres, etc.) for combined analysis- **Data pipelines (CDP)** – import data from 20+ sources, transform events in real-time, and export to external destinationsdiff --git a/ee/hogai/research_agent/prompts/base.py b/ee/hogai/research_agent/prompts/base.pyindex fde1d314212f..9e9a55895bea 100644--- a/ee/hogai/research_agent/prompts/base.py+++ b/ee/hogai/research_agent/prompts/base.py@@ -26,6 +26,7 @@ Created data is used by the user on the PostHog's website to perform business ac- Feature flags – feature flags that the user creates to control the feature rollout in their product.- Notebooks – notebooks that the user creates to perform business analysis.- Error tracking issues – issues that the user creates to track errors in their product.+- User interview topics – topics that drive AI voice agent interviews with selected users, with questions you author.Before using a tool, say what you're about to do, in one sentence.Do not generate any code like Python scripts. Users don't have the ability to run code.diff --git a/frontend/src/layout/navigation-3000/Navigation.tsx b/frontend/src/layout/navigation-3000/Navigation.tsxindex 10d82077dbf5..60e59fcb304c 100644--- a/frontend/src/layout/navigation-3000/Navigation.tsx+++ b/frontend/src/layout/navigation-3000/Navigation.tsx@@ -7,6 +7,7 @@ import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShimport { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { cn } from 'lib/utils/css-classes'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'+import { useMaxTool } from 'scenes/max/useMaxTool'import { sceneLogic } from 'scenes/sceneLogic'import { SceneConfig } from 'scenes/sceneTypes'@@ -34,6 +35,15 @@ export function Navigation({sceneConfig: SceneConfig | null}): JSX.Element {useMountedLogic(maxGlobalLogic)+ const userInterviewsEnabled = useFeatureFlag('USER_INTERVIEWS')+ // Register `create_user_interview_topic` globally so Max can create user interview+ // topics from any page (including the homepage), not only from the user-interviews+ // scene. The scene wires its own richer `useMaxTool` for the "New topic" button.+ useMaxTool({+ identifier: 'create_user_interview_topic',+ active: userInterviewsEnabled,+ context: {},+ })const { theme } = useValues(themeLogic)const { mobileLayout } = useValues(navigationLogic)const { mode } = useValues(navigation3000Logic)diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 613baa8fcb00..16fa302876f6 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -3512,6 +3512,7 @@"search_session_recordings","fix_hogql_query","analyze_user_interviews",+ "create_user_interview_topic","create_hog_transformation_function","create_hog_function_filters","create_hog_function_inputs",diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex cb61683f091a..8885ca8dc25f 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -452,6 +452,7 @@ export type AssistantTool =| 'search_session_recordings'| 'fix_hogql_query'| 'analyze_user_interviews'+ | 'create_user_interview_topic'| 'create_hog_transformation_function'| 'create_hog_function_filters'| 'create_hog_function_inputs'diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex a7956fb2091c..7ca3035a8b46 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -542,6 +542,19 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {return 'Analyzing user interviews...'},},+ create_user_interview_topic: {+ name: 'Set up user interviews',+ description: 'Set up user interviews — plan a research topic, target participants, and draft questions',+ product: Scene.UserInterviews,+ flag: FEATURE_FLAGS.USER_INTERVIEWS,+ icon: iconForType('user_interview'),+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Created interview topic'+ }+ return 'Setting up interview topic...'+ },+ },create_hog_function_filters: {name: 'Set up function filters',description: 'Set up function filters for quick pipeline configuration',diff --git a/posthog/schema.py b/posthog/schema.pyindex e7d464bcc324..a5cf24a60558 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -687,6 +687,7 @@ class AssistantTool(StrEnum):SEARCH_SESSION_RECORDINGS = "search_session_recordings"FIX_HOGQL_QUERY = "fix_hogql_query"ANALYZE_USER_INTERVIEWS = "analyze_user_interviews"+ CREATE_USER_INTERVIEW_TOPIC = "create_user_interview_topic"CREATE_HOG_TRANSFORMATION_FUNCTION = "create_hog_transformation_function"CREATE_HOG_FUNCTION_FILTERS = "create_hog_function_filters"CREATE_HOG_FUNCTION_INPUTS = "create_hog_function_inputs"diff --git a/products/user_interviews/backend/max_tools.py b/products/user_interviews/backend/max_tools.pyindex 613e430c3062..e05706ffa7b9 100644--- a/products/user_interviews/backend/max_tools.py+++ b/products/user_interviews/backend/max_tools.py@@ -1,13 +1,23 @@+from textwrap import dedentfrom typing import Anyfrom django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom openai import OpenAI-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Field++from posthog.exceptions_capture import capture_exception+from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObjectfrom ee.hogai.tool import MaxTool-from .models import UserInterview+from .models import EmailWithDisplayNameValidator, UserInterview, UserInterviewTopic+++def _topic_url(topic_id: str) -> str:+ return f"/user_research/{topic_id}"class AnalyzeUserInterviewsArgs(BaseModel):@@ -68,3 +78,202 @@ Provide a structured analysis with clear sections and bullet points where approp)return analysis_response.output_text, None+++CREATE_USER_INTERVIEW_TOPIC_DESCRIPTION = dedent("""+ Create a user research interview topic — a planned voice-AI interview campaign.++ # When to use+ - The user wants to set up or run user interviews, user research, customer research,+ or "talk to users" about a feature, product area, or hypothesis.+ - The user asks to plan, schedule, draft, or kick off user interviews.++ # What this creates+ A `UserInterviewTopic` containing who to talk to (`interviewee_emails` and/or+ `interviewee_distinct_ids`), the research topic, optional context for the AI voice+ agent, and the ordered list of questions it should work through. After creation, the+ user can generate per-interviewee public links from the topic page and email invites+ to participants. The voice agent handles the live call.++ # Required information+ - `topic`: short statement of what to learn (e.g. "the new dashboard onboarding flow").+ - At least one of `interviewee_emails` OR `interviewee_distinct_ids` must be non-empty.+ Emails are preferred when known — invites can be sent automatically. PostHog distinct+ IDs work too but cannot receive email invites until an email is added.+ - `questions`: 3-6 focused, open-ended questions in the order the agent should ask+ them. Keep them conversational and avoid leading or yes/no phrasings.++ # Optional+ - `agent_context`: extra background for the voice agent — tone, what the product+ does, what NOT to ask about, who the interviewer "is" representing. Becomes part+ of the agent's system prompt for every call on this topic.++ # Important+ - This is NOT a survey. Do NOT use `create_survey` when the user asks for an+ interview, research call, or "talk to users" — those are live AI voice+ conversations, not in-app survey widgets.+ - This is NOT a session recording filter. Do NOT redirect to session recordings+ or replays when the user wants to interview people.+ - Do not invent emails or distinct IDs. If the user has not provided participants+ and you cannot derive them from the available cohort/persons tools, ask the user.+ """).strip()+++class CreateUserInterviewTopicArgs(BaseModel):+ model_config = ConfigDict(extra="ignore")++ topic: str = Field(+ description=(+ "Short statement of what you want to learn from the interviews — the product "+ "area, feature, or hypothesis being researched."+ ),+ )+ interviewee_emails: list[str] = Field(+ default_factory=list,+ description=(+ "Email addresses of people to interview. Accepts plain `email@host` or the "+ "`Display Name <email@host>` form. May be combined with `interviewee_distinct_ids` "+ "but at least one of the two lists must be non-empty."+ ),+ )+ interviewee_distinct_ids: list[str] = Field(+ default_factory=list,+ description=(+ "PostHog distinct IDs of people to interview. May be combined with "+ "`interviewee_emails`, but at least one of the two lists must be non-empty. "+ "Distinct-ID-only interviewees cannot receive email invites until they are "+ "given an email address."+ ),+ )+ questions: list[str] = Field(+ default_factory=list,+ description=(+ "Ordered list of questions the AI voice agent should work through during the "+ "interview. Keep questions open-ended, conversational, and focused on the topic."+ ),+ )+ agent_context: str = Field(+ default="",+ description=(+ "Optional extra context for the voice agent — background on the product, "+ "tone, or constraints. Becomes part of the agent's system prompt for every "+ "call on this topic. Leave empty if no extra context is needed."+ ),+ )+++class CreateUserInterviewTopicTool(MaxTool):+ name: str = "create_user_interview_topic"+ description: str = CREATE_USER_INTERVIEW_TOPIC_DESCRIPTION+ context_prompt_template: str = (+ "When the user explicitly wants to interview users, talk to users live, or run "+ "user research calls, prefer `create_user_interview_topic`. For passive, in-app "+ "feedback (e.g. NPS, opinion polls, ratings), `create_survey` is still the right "+ "choice."+ )+ args_schema: type[BaseModel] = CreateUserInterviewTopicArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("user_interview", "editor")]++ async def _arun_impl(+ self,+ topic: str = "",+ interviewee_emails: list[str] | None = None,+ interviewee_distinct_ids: list[str] | None = None,+ questions: list[str] | None = None,+ agent_context: str = "",+ ) -> tuple[str, dict[str, Any]]:+ emails = [e.strip() for e in (interviewee_emails or []) if e and e.strip()]+ distinct_ids = [d.strip() for d in (interviewee_distinct_ids or []) if d and d.strip()]+ questions = [q.strip() for q in (questions or []) if q and q.strip()]+ topic = (topic or "").strip()++ if not topic:+ return "Topic is required.", {+ "error": "validation_failed",+ "error_message": "Topic must be a non-empty string describing what you want to learn.",+ }++ if not emails and not distinct_ids:+ return (+ "At least one interviewee email or PostHog distinct ID must be provided.",+ {+ "error": "validation_failed",+ "error_message": (+ "Provide at least one entry in `interviewee_emails` or "+ "`interviewee_distinct_ids` so we know who to interview."+ ),+ },+ )++ if not questions:+ return (+ "At least one interview question is required.",+ {+ "error": "validation_failed",+ "error_message": (+ "Provide at least one question in `questions`. "+ "The AI voice agent needs questions to ask during the interview."+ ),+ },+ )++ validator = EmailWithDisplayNameValidator()+ invalid_emails: list[str] = []+ for email in emails:+ try:+ validator(email)+ except DjangoValidationError:+ invalid_emails.append(email)+ if invalid_emails:+ return (+ f"Invalid email address(es): {', '.join(invalid_emails)}",+ {+ "error": "validation_failed",+ "error_message": (+ "These values are not valid email addresses: "+ + ", ".join(invalid_emails)+ + ". Use plain `email@host` or `Display Name <email@host>`."+ ),+ },+ )++ try:+ created_topic = await UserInterviewTopic.objects.acreate(+ team=self._team,+ created_by=self._user,+ topic=topic,+ interviewee_emails=emails,+ interviewee_distinct_ids=distinct_ids,+ questions=questions,+ agent_context=agent_context or "",+ )+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to create interview topic: {str(e)}", {+ "error": "creation_failed",+ "error_message": str(e),+ }++ topic_id = str(created_topic.id)+ topic_url = _topic_url(topic_id)+ targeting_summary_parts = []+ if emails:+ targeting_summary_parts.append(f"{len(emails)} email{'s' if len(emails) != 1 else ''}")+ if distinct_ids:+ targeting_summary_parts.append(f"{len(distinct_ids)} distinct ID{'s' if len(distinct_ids) != 1 else ''}")+ targeting_summary = " + ".join(targeting_summary_parts) or "no interviewees"++ message = (+ f"Created interview topic '{topic}' targeting {targeting_summary} with "+ f"{len(questions)} question{'s' if len(questions) != 1 else ''}. "+ f"[Open topic]({topic_url}) to generate links or send invites."+ )+ return message, {+ "topic_id": topic_id,+ "topic": created_topic.topic,+ "interviewee_email_count": len(emails),+ "interviewee_distinct_id_count": len(distinct_ids),+ "question_count": len(questions),+ }diff --git a/products/user_interviews/backend/test_max_tools.py b/products/user_interviews/backend/test_max_tools.pynew file mode 100644index 000000000000..9c3831ae78bf--- /dev/null+++ b/products/user_interviews/backend/test_max_tools.py@@ -0,0 +1,133 @@+import pytest+from posthog.test.base import BaseTest++from asgiref.sync import sync_to_async+from langchain_core.runnables import RunnableConfig+from parameterized import parameterized++from products.user_interviews.backend.models import UserInterviewTopic++from .max_tools import CreateUserInterviewTopicTool+++class TestCreateUserInterviewTopicTool(BaseTest):+ def setUp(self):+ super().setUp()+ self._config: RunnableConfig = {+ "configurable": {+ "team": self.team,+ "user": self.user,+ },+ }++ def _tool(self) -> CreateUserInterviewTopicTool:+ return CreateUserInterviewTopicTool(team=self.team, user=self.user, config=self._config)++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_arun_impl_success_with_emails(self):+ tool = self._tool()++ content, artifact = await tool._arun_impl(+ topic="Onboarding experience",+ interviewee_emails=["[email protected]", "Sam <[email protected]>"],+ questions=[+ "What were you hoping to achieve when you signed up?",+ "Where did you get stuck during onboarding?",+ "What would have made the first 5 minutes easier?",+ ],+ agent_context="Focus on emotional friction, not feature requests.",+ )++ assert "Created interview topic" in content+ assert artifact["topic"] == "Onboarding experience"+ assert artifact["interviewee_email_count"] == 2+ assert artifact["interviewee_distinct_id_count"] == 0+ assert artifact["question_count"] == 3++ topic = await sync_to_async(+ lambda: UserInterviewTopic.objects.select_related("team", "created_by").get(+ team=self.team, id=artifact["topic_id"]+ )+ )()+ assert topic.team == self.team+ assert topic.created_by == self.user+ assert topic.interviewee_emails == ["[email protected]", "Sam <[email protected]>"]+ assert topic.interviewee_distinct_ids == []+ assert len(topic.questions) == 3+ assert topic.agent_context == "Focus on emotional friction, not feature requests."++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_arun_impl_success_with_distinct_ids_only(self):+ tool = self._tool()++ content, artifact = await tool._arun_impl(+ topic="Power user dashboard usage",+ interviewee_distinct_ids=["user_123", "user_456"],+ questions=["How do you currently use dashboards?"],+ )++ assert "Created interview topic" in content+ assert artifact["interviewee_email_count"] == 0+ assert artifact["interviewee_distinct_id_count"] == 2++ @pytest.mark.django_db+ @pytest.mark.asyncio+ @parameterized.expand(+ [+ (+ "empty_topic",+ {"topic": " ", "interviewee_emails": ["[email protected]"]},+ "topic is required",+ ),+ (+ "no_interviewees",+ {"topic": "Some topic", "interviewee_emails": [], "interviewee_distinct_ids": []},+ "interviewee",+ ),+ (+ "invalid_emails",+ {+ "topic": "Some topic",+ "interviewee_emails": ["not-an-email", "also bad"],+ "questions": ["A question?"],+ },+ "not-an-email",+ ),+ (+ "no_questions",+ {"topic": "Some topic", "interviewee_emails": ["[email protected]"], "questions": []},+ "question",+ ),+ ]+ )+ async def test_arun_impl_rejects_invalid_input(self, _name, kwargs, expected_content_fragment):+ tool = self._tool()++ content, artifact = await tool._arun_impl(**kwargs)++ assert artifact["error"] == "validation_failed"+ assert expected_content_fragment in content.lower()+ assert not await sync_to_async(UserInterviewTopic.objects.filter(team=self.team).exists)()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_arun_impl_strips_blank_entries(self):+ tool = self._tool()++ content, artifact = await tool._arun_impl(+ topic="Some topic",+ interviewee_emails=["[email protected]", " ", ""],+ interviewee_distinct_ids=["", "user_1"],+ questions=["A real question?", " ", ""],+ )++ assert artifact["interviewee_email_count"] == 1+ assert artifact["interviewee_distinct_id_count"] == 1+ assert artifact["question_count"] == 1++ topic = await sync_to_async(lambda: UserInterviewTopic.objects.get(team=self.team, id=artifact["topic_id"]))()+ assert topic.interviewee_emails == ["[email protected]"]+ assert topic.interviewee_distinct_ids == ["user_1"]+ assert topic.questions == ["A real question?"]diff --git a/products/user_interviews/frontend/UserInterviews.tsx b/products/user_interviews/frontend/UserInterviews.tsxindex 8611a315e1bb..faec866f2674 100644--- a/products/user_interviews/frontend/UserInterviews.tsx+++ b/products/user_interviews/frontend/UserInterviews.tsx@@ -1,17 +1,16 @@-import { useActions, useValues } from 'kea'+import { useValues } from 'kea'import { IconSparkles } from '@posthog/icons'import { LemonButton, LemonTable } from '@posthog/lemon-ui'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { useMaxTool } from 'scenes/max/useMaxTool'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'-import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { SidePanelTab } from '~/types'import type { UserInterviewTopicApi } from './generated/api.schemas'import { userInterviewsLogic } from './userInterviewsLogic'@@ -34,19 +33,28 @@ function targetingLabel(topic: UserInterviewTopicApi): string {return parts.length > 0 ? parts.join(' + ') : 'Not set'}-const NEW_TOPIC_PROMPT = `!I want to set up a new user research topic. Help me through the process:+const NEW_TOPIC_PROMPT = `!I want to set up a new user research topic. Help me work through:+1. What I want to learn — the feature, behavior, or question to research.+2. Who to interview — let me give you emails or distinct IDs, or help me pick from a cohort.+3. The interview questions — 3-6 open-ended, conversational prompts in a sensible order.+Then create the topic using the create_user_interview_topic tool. Don't try to send emails or generate links yourself — once the topic exists I'll do that from the topic page.`-1. First, let's figure out what I want to learn — what feature, behavior, or question I want to research.-2. Then, help me identify the right users to interview — pick a cohort, find users by behavior, or provide emails directly.-3. Draft interview questions based on the topic.-4. Set up the outreach workflow to email each user with their unique interview link.-5. Once I confirm, trigger the emails — I'll track responses in User research.--Let's start — ask me what I want to learn about.`+const NEW_TOPIC_SUGGESTIONS = [+ 'Interview recent signups about their onboarding experience',+ 'Talk to power users about what they wish the product did better',+ 'Interview customers who churned in the last 30 days',+ 'Research how teams are using dashboards day-to-day',+]export function UserInterviews(): JSX.Element {const { topics, topicsLoading } = useValues(userInterviewsLogic)- const { openSidePanel } = useActions(sidePanelStateLogic)++ const { openMax } = useMaxTool({+ identifier: 'create_user_interview_topic',+ context: {},+ initialMaxPrompt: NEW_TOPIC_PROMPT,+ suggestions: NEW_TOPIC_SUGGESTIONS,+ })return (<SceneContent>@@ -61,7 +69,8 @@ export function UserInterviews(): JSX.Element {type="primary"icon={<IconSparkles />}data-attr="new-topic"- onClick={() => openSidePanel(SidePanelTab.Max, NEW_TOPIC_PROMPT)}+ onClick={() => openMax?.()}+ disabledReason={openMax ? undefined : 'PostHog AI is unavailable here'}>New topic</LemonButton>