Skip to content

: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.

feat(user-interviews): templated first message via PostHog prompt management (#58722)

Paul D'Ambraf5f4b9451e29
diff --git a/frontend/src/lib/utils/router-utils.ts b/frontend/src/lib/utils/router-utils.ts
index b045d5870786..852bbf221518 100644
--- a/frontend/src/lib/utils/router-utils.ts
+++ b/frontend/src/lib/utils/router-utils.ts
@@ -15,6 +15,7 @@ const pathsWithoutProjectId = [
'oauth',
'shared',
'embedded',
+ 'interview',
'cli',
'render_query',
]
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index de1019b59a29..7a1475c10257 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -20,7 +20,13 @@ from posthog.models.sharing_configuration import SharingConfiguration
from products.user_interviews.backend.api import UserInterviewTopicSerializer
from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic
-from products.user_interviews.backend.webhooks import EMBEDDING_CONTENT_MAX_BYTES, _build_first_message
+from products.user_interviews.backend.webhooks import (
+ DEFAULT_FIRST_MESSAGE_TEMPLATE,
+ EMBEDDING_CONTENT_MAX_BYTES,
+ FIRST_MESSAGE_PROMPT_NAME,
+ _build_first_message,
+ _resolve_first_message_template,
+)
class _FeatureFlagEnabledMixin(APIBaseTest):
@@ -328,44 +334,112 @@ class TestInterviewPublicViewer(APIBaseTest):
class TestBuildFirstMessage(unittest.TestCase):
@parameterized.expand(
[
- ("simple_name_and_topic", "Paul", "taxonomic filter search", ["Hi Paul!", "taxonomic filter search"]),
- ("dotted_local_part", "Cory S", "session replay adoption", ["Hi Cory S!", "session replay adoption"]),
+ ("simple_name_and_topic", "Paul", "taxonomic filter search", ["Hey Paul!", "taxonomic filter search"]),
+ ("dotted_local_part", "Cory S", "session replay adoption", ["Hey Cory S!", "session replay adoption"]),
(
"name_with_trailing_topic_whitespace",
"Kim",
" feature flag rollout ",
- ["Hi Kim!", "feature flag rollout"],
+ ["Hey Kim!", "feature flag rollout"],
),
]
)
def test_includes_name_and_topic(self, _label: str, user_name: str, topic_text: str, expected_fragments: list[str]):
- message = _build_first_message(user_name=user_name, topic_text=topic_text)
+ message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name=user_name, topic_text=topic_text)
for fragment in expected_fragments:
assert fragment in message
@parameterized.expand([("empty", ""), ("whitespace_only", " ")])
- def test_drops_topic_sentence_when_topic_empty(self, _label: str, topic_text: str):
- message = _build_first_message(user_name="Sam", topic_text=topic_text)
- assert "Hi Sam!" in message
- assert "Today we're talking about" not in message
+ def test_falls_back_to_generic_topic_when_topic_empty(self, _label: str, topic_text: str):
+ message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text=topic_text)
+ assert "Hey Sam!" in message
+ assert "your experience" in message
@parameterized.expand([("empty", ""), ("whitespace_only", " ")])
def test_falls_back_to_generic_greeting_when_user_name_empty(self, _label: str, user_name: str):
- message = _build_first_message(user_name=user_name, topic_text="checkout funnel")
- assert "Hi there!" in message
- assert "Hi !" not in message
+ message = _build_first_message(
+ DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name=user_name, topic_text="checkout funnel"
+ )
+ assert "Hey there!" in message
+ assert "Hey !" not in message
def test_collapses_internal_whitespace_in_topic(self):
- message = _build_first_message(user_name="Sam", topic_text="multi\nline\n\ttopic")
+ message = _build_first_message(
+ DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text="multi\nline\n\ttopic"
+ )
assert "multi line topic" in message
assert "\n" not in message
def test_truncates_very_long_topic(self):
long_topic = "x" * 500
- message = _build_first_message(user_name="Sam", topic_text=long_topic)
+ message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="Sam", topic_text=long_topic)
assert "x" * 200 in message
assert "x" * 201 not in message
+ def test_uses_custom_template_when_provided(self):
+ custom = "Hi $user_name, today's topic: $topic_text."
+ message = _build_first_message(custom, user_name="Paul", topic_text="onboarding")
+ assert message == "Hi Paul, today's topic: onboarding."
+
+ def test_falls_back_to_default_when_custom_template_missing_placeholder(self):
+ broken = "Hi $nonsense, today is $missing_field."
+ message = _build_first_message(broken, user_name="Paul", topic_text="onboarding")
+ assert "Hey Paul!" in message
+ assert "onboarding" in message
+
+ def test_format_spec_in_template_is_treated_as_literal_text(self):
+ # string.Template has no format-spec syntax, so an attacker cannot use
+ # `{user_name:>10000000000}` to allocate gigabytes — `:` is just a character.
+ attempted = "Hi $user_name, padded: {user_name:>10000000000}"
+ message = _build_first_message(attempted, user_name="Paul", topic_text="onboarding")
+ assert "Hi Paul" in message
+ assert len(message) <= 1000
+
+ def test_falls_back_to_default_when_rendered_message_exceeds_cap(self):
+ huge = "Hi $user_name! " + ("x" * 2000)
+ message = _build_first_message(huge, user_name="Paul", topic_text="onboarding")
+ assert "Hey Paul!" in message
+ assert "onboarding" in message
+ assert len(message) <= 1000
+
+ def test_return_value_is_always_bounded_even_with_long_user_name(self):
+ message = _build_first_message(DEFAULT_FIRST_MESSAGE_TEMPLATE, user_name="x" * 5000, topic_text="onboarding")
+ assert len(message) <= 1000
+
+
+class TestResolveFirstMessageTemplate(APIBaseTest):
+ def test_returns_default_when_no_prompt_configured(self):
+ template = _resolve_first_message_template(self.team)
+ assert template == DEFAULT_FIRST_MESSAGE_TEMPLATE
+
+ def test_returns_team_override_when_prompt_published(self):
+ from posthog.models.llm_prompt import LLMPrompt
+
+ LLMPrompt.objects.create(
+ team=self.team,
+ name=FIRST_MESSAGE_PROMPT_NAME,
+ prompt="Hey $user_name! Quick chat about $topic_text?",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ template = _resolve_first_message_template(self.team)
+ assert template == "Hey $user_name! Quick chat about $topic_text?"
+
+ def test_returns_default_when_published_prompt_is_empty(self):
+ from posthog.models.llm_prompt import LLMPrompt
+
+ LLMPrompt.objects.create(
+ team=self.team,
+ name=FIRST_MESSAGE_PROMPT_NAME,
+ prompt=" ",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ template = _resolve_first_message_template(self.team)
+ assert template == DEFAULT_FIRST_MESSAGE_TEMPLATE
+
class TestInterviewStartCall(APIBaseTest):
def _create_share(self) -> SharingConfiguration:
@@ -409,7 +483,7 @@ class TestInterviewStartCall(APIBaseTest):
response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
assert response.status_code == status.HTTP_200_OK, response.content
first_message = response.json()["assistant_overrides"]["firstMessage"]
- assert "Hi Alex!" in first_message
+ assert "Hey Alex!" in first_message
assert "Replay adoption" in first_message
@override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
diff --git a/products/user_interviews/backend/webhooks.py b/products/user_interviews/backend/webhooks.py
index 5f961e3ef77a..8d857b7e34de 100644
--- a/products/user_interviews/backend/webhooks.py
+++ b/products/user_interviews/backend/webhooks.py
@@ -11,6 +11,7 @@ Two surfaces live here, both keyed on a SharingConfiguration access token:
import hmac
import json
+import string
import hashlib
from typing import Any
@@ -31,6 +32,8 @@ from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import emit_embedding_request
from posthog.constants import AvailableFeature
from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.models.team import Team
+from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
from .models import UserInterview, UserInterviewTopic
@@ -131,20 +134,69 @@ def _public_sharing_disabled_for_org(sharing_config: SharingConfiguration) -> bo
_TOPIC_MAX_CHARS = 200
+FIRST_MESSAGE_PROMPT_NAME = "user_interviews_vapi_first_message"
+
+DEFAULT_FIRST_MESSAGE_TEMPLATE = (
+ "Hey $user_name! Thanks for making time — I know you're busy. "
+ "I'm here to learn how you actually use $topic_text in the wild. "
+ "Mind if I ask a few questions? Should take about 5-10 minutes."
+)
+
+_FIRST_MESSAGE_MAX_CHARS = 1000
+
def _normalise_topic(topic_text: str) -> str:
return " ".join(topic_text.split())[:_TOPIC_MAX_CHARS]
-def _build_first_message(*, user_name: str, topic_text: str) -> str:
- name_part = f"Hi {user_name.strip()}!" if user_name.strip() else "Hi there!"
- greeting = f"{name_part} Thanks for joining."
- topic_normalised = _normalise_topic(topic_text)
- if topic_normalised:
- return (
- f"{greeting} Today we're talking about {topic_normalised}. I'd love your perspective. Ready when you are."
+def _resolve_first_message_template(team: Team) -> str:
+ try:
+ cached = get_prompt_by_name_from_cache(team, FIRST_MESSAGE_PROMPT_NAME)
+ except Exception as err:
+ logger.warning(
+ "user_interviews_first_message_prompt_lookup_failed",
+ team_id=team.id,
+ error=str(err),
)
- return f"{greeting} I'd love your perspective. Ready when you are."
+ return DEFAULT_FIRST_MESSAGE_TEMPLATE
+ if cached is not None:
+ template = cached.get("prompt")
+ if isinstance(template, str) and template.strip():
+ return template
+ return DEFAULT_FIRST_MESSAGE_TEMPLATE
+
+
+def _build_first_message(
+ template: str,
+ *,
+ user_name: str,
+ topic_text: str,
+ team_id: int | None = None,
+) -> str:
+ name_part = user_name.strip() or "there"
+ topic_part = _normalise_topic(topic_text) or "your experience"
+ try:
+ rendered = string.Template(template).substitute(user_name=name_part, topic_text=topic_part)
+ except (KeyError, ValueError):
+ logger.warning(
+ "user_interviews_first_message_template_invalid",
+ team_id=team_id,
+ template_prefix=template[:60],
+ )
+ rendered = string.Template(DEFAULT_FIRST_MESSAGE_TEMPLATE).substitute(
+ user_name=name_part, topic_text=topic_part
+ )
+ if len(rendered) > _FIRST_MESSAGE_MAX_CHARS:
+ logger.warning(
+ "user_interviews_first_message_too_long",
+ team_id=team_id,
+ rendered_chars=len(rendered),
+ limit=_FIRST_MESSAGE_MAX_CHARS,
+ )
+ rendered = string.Template(DEFAULT_FIRST_MESSAGE_TEMPLATE).substitute(
+ user_name=name_part, topic_text=topic_part
+ )
+ return rendered[:_FIRST_MESSAGE_MAX_CHARS]
@api_view(["POST"])
@@ -188,7 +240,13 @@ def start_call(request: Request, access_token: str) -> Response:
topic = ic.topic
user_name, _ = _parse_identifier(ic.interviewee_identifier)
agent_context = _merge_agent_context(topic.agent_context or "", ic.agent_context or "")
- first_message = _build_first_message(user_name=user_name, topic_text=topic.topic or "")
+ first_message_template = _resolve_first_message_template(sharing_config.team)
+ first_message = _build_first_message(
+ first_message_template,
+ user_name=user_name,
+ topic_text=topic.topic or "",
+ team_id=sharing_config.team_id,
+ )
logger.info(
"user_interviews_start_call_issued",