: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): semantic search across interview responses (#58605)
Paul D'Ambra73e0dfa2e68a
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex bca1e2e93aac..57507c1b37d6 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -54,6 +54,7 @@ class Product(StrEnum):SESSION_SUMMARY = "session_summary"SIGNALS = "signals"SURVEYS = "surveys"+ USER_INTERVIEWS = "user_interviews"WAREHOUSE = "warehouse"WEB_ANALYTICS = "web_analytics"WORKFLOWS = "workflows"@@ -101,6 +102,7 @@ class Feature(StrEnum):ENDPOINT_LAST_EXECUTION = "endpoint_last_execution" # Usage tab query_log lookupPOSTHOG_AI = "posthog_ai"MCP = "mcp"+ SEMANTIC_SEARCH = "semantic_search"class FallbackTags(TypedDict):diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e682ba110ed7..8cceae46a322 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -434,6 +434,7 @@ SPECTACULAR_SETTINGS = {"LensProviderEnum": "products.replay_vision.backend.models.replay_lens.LensProvider","ObservationStatusEnum": "products.replay_vision.backend.models.replay_observation.ObservationStatus","ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger",+ "UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.api.SEARCH_DOCUMENT_TYPES",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],"PropertyFilterTypeEnum": [diff --git a/products/legal_documents/frontend/generated/api.schemas.ts b/products/legal_documents/frontend/generated/api.schemas.tsindex 7091b2d7e004..27aece1c7e62 100644--- a/products/legal_documents/frontend/generated/api.schemas.ts+++ b/products/legal_documents/frontend/generated/api.schemas.ts@@ -38,9 +38,10 @@ export interface PaginatedLegalDocumentDTOListApi {* * `BAA` - BAA* `DPA` - DPA*/-export type DocumentTypeEnumApi = (typeof DocumentTypeEnumApi)[keyof typeof DocumentTypeEnumApi]+export type CreateLegalDocumentDocumentTypeEnumApi =+ (typeof CreateLegalDocumentDocumentTypeEnumApi)[keyof typeof CreateLegalDocumentDocumentTypeEnumApi]-export const DocumentTypeEnumApi = {+export const CreateLegalDocumentDocumentTypeEnumApi = {Baa: 'BAA',Dpa: 'DPA',} as const@@ -55,7 +56,7 @@ export interface CreateLegalDocumentApi {* `BAA` - BAA* `DPA` - DPA */- document_type: DocumentTypeEnumApi+ document_type: CreateLegalDocumentDocumentTypeEnumApi/*** The customer legal entity entering the agreement (PandaDoc's Client.Company).* @maxLength 255diff --git a/products/user_interviews/backend/api.py b/products/user_interviews/backend/api.pyindex df7d1524ecb9..c36e157b2bcf 100644--- a/products/user_interviews/backend/api.py+++ b/products/user_interviews/backend/api.py@@ -10,6 +10,7 @@ from django.db import modelsfrom django.db.models import QuerySetfrom django.utils import timezone+import structlogimport posthoganalyticsimport posthoganalytics.ai.openaifrom django_filters.rest_framework import DjangoFilterBackend@@ -21,10 +22,16 @@ from rest_framework.decorators import actionfrom rest_framework.parsers import JSONParser, MultiPartParserfrom rest_framework.request import Request-from posthog.schema import ProductKey+from posthog.schema import EmbeddingModelName, ProductKey+from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.api.embedding_worker import generate_embedding+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.email import EmailMessage, is_email_availablefrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.permissions import PostHogFeatureFlagPermission@@ -32,6 +39,8 @@ from posthog.utils import absolute_urifrom .models import EmailWithDisplayNameValidator, IntervieweeContext, UserInterview, UserInterviewTopic+logger = structlog.get_logger(__name__)+elevenlabs_client = ElevenLabs()@@ -232,6 +241,71 @@ Record the agreed-upon next steps, including any additional actions that need toreturn str(uuid4())+SEARCH_DOCUMENT_TYPES = ("transcript", "summary")+SEARCH_EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072.value+SEARCH_CONTENT_SNIPPET_LIMIT = 500+SEARCH_MAX_LIMIT = 50+SEARCH_DEFAULT_LIMIT = 10+# Pathological-size guard for topic_id-scoped searches — a topic with more than this many+# interviews ships a giant IN list to ClickHouse. Realistic topics are tiny (<100); the+# cap exists to keep the worst case bounded.+SEARCH_TOPIC_INTERVIEW_CAP = 1000+++class UserInterviewSearchRequestSerializer(serializers.Serializer):+ query = serializers.CharField(+ max_length=2000,+ help_text="Natural-language query to match semantically against interview transcripts and summaries.",+ )+ document_types = serializers.ListField(+ child=serializers.ChoiceField(choices=list(SEARCH_DOCUMENT_TYPES)),+ required=False,+ allow_empty=False,+ min_length=1,+ help_text=(+ "Which document types to search across. Omit to default to both "+ "`transcript` and `summary`. Pass a non-empty subset to restrict the search."+ ),+ )+ topic_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.",+ )+ limit = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=SEARCH_MAX_LIMIT,+ help_text=(+ f"Maximum number of matches to return (1-{SEARCH_MAX_LIMIT}). "+ f"Defaults to {SEARCH_DEFAULT_LIMIT}. Two matches per interview are possible — "+ "one for the transcript, one for the summary."+ ),+ )+++class UserInterviewSearchResultSerializer(serializers.Serializer):+ interview_id = serializers.UUIDField(help_text="ID of the matched UserInterview.")+ document_type = serializers.ChoiceField(+ choices=list(SEARCH_DOCUMENT_TYPES),+ help_text="Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.",+ )+ similarity = serializers.FloatField(+ help_text="Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`.",+ )+ content_snippet = serializers.CharField(+ help_text=f"Excerpt of the matched document (first {SEARCH_CONTENT_SNIPPET_LIMIT} characters).",+ )+ interviewee_identifier = serializers.CharField(+ help_text="Email or PostHog distinct ID of the interviewee.",+ )+ topic_id = serializers.UUIDField(+ allow_null=True,+ help_text="ID of the UserInterviewTopic the interview was conducted for, or null if detached.",+ )+ created_at = serializers.DateTimeField(help_text="When the interview row was created.")++@extend_schema(tags=[ProductKey.USER_INTERVIEWS])class UserInterviewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "user_interview"@@ -243,6 +317,144 @@ class UserInterviewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):filter_backends = [DjangoFilterBackend]filterset_fields = ["topic"]+ @validated_request(+ request_serializer=UserInterviewSearchRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=UserInterviewSearchResultSerializer(many=True),+ description="Matches ranked by cosine similarity (descending).",+ ),+ },+ summary="Search interview responses by semantic similarity",+ description=(+ "Embed `query` with the same model used to index interview transcripts and summaries, "+ "then return the top matches by cosine distance. Each match is a single (interview, "+ "document_type) pair — an interview can appear up to twice if both its transcript and "+ "summary score above other interviews. Useful for surfacing relevant interview snippets "+ "in natural language, without exact keyword matches."+ ),+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="search",+ pagination_class=None,+ parser_classes=[JSONParser],+ required_scopes=["user_interview:read"],+ )+ def search(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> response.Response:+ body = request.validated_data+ query_str: str = body["query"]+ document_types: list[str] = body.get("document_types") or list(SEARCH_DOCUMENT_TYPES)+ topic_id = body.get("topic_id")+ limit: int = body.get("limit") or SEARCH_DEFAULT_LIMIT++ # When a topic_id filter is requested, resolve it via the current Postgres linkage+ # rather than the embedding-time `metadata.topic_id` — UserInterview.topic is+ # nullable with on_delete=SET_NULL, so historical metadata can name a topic the+ # row no longer belongs to.+ scoped_document_ids: list[str] | None = None+ if topic_id is not None:+ scoped_ids_qs = (+ UserInterview.objects.filter(team_id=self.team_id, topic_id=topic_id)+ .order_by("id")+ .values_list("id", flat=True)[: SEARCH_TOPIC_INTERVIEW_CAP + 1]+ )+ scoped_document_ids = [str(pk) for pk in scoped_ids_qs]+ if not scoped_document_ids:+ return response.Response(UserInterviewSearchResultSerializer([], many=True).data)+ if len(scoped_document_ids) > SEARCH_TOPIC_INTERVIEW_CAP:+ logger.warning(+ "user_interviews_search_topic_scope_capped",+ team_id=self.team_id,+ topic_id=str(topic_id),+ cap=SEARCH_TOPIC_INTERVIEW_CAP,+ )+ scoped_document_ids = scoped_document_ids[:SEARCH_TOPIC_INTERVIEW_CAP]++ try:+ embedding_response = generate_embedding(self.team, query_str, model=SEARCH_EMBEDDING_MODEL)+ except Exception:+ logger.exception(+ "user_interviews_search_embedding_failed",+ team_id=self.team_id,+ query_length=len(query_str),+ )+ return response.Response(+ {"detail": "Embedding service is currently unavailable. Please retry shortly."},+ status=status.HTTP_502_BAD_GATEWAY,+ )+ query_vector = embedding_response.embedding++ where_clauses = [+ "model_name = {model_name}",+ "product = {product}",+ "team_id = {team_id}",+ "document_type IN {document_types}",+ ]+ placeholders: dict[str, ast.Expr] = {+ "embedding": ast.Constant(value=query_vector),+ "model_name": ast.Constant(value=SEARCH_EMBEDDING_MODEL),+ "product": ast.Constant(value=Product.USER_INTERVIEWS.value),+ "team_id": ast.Constant(value=self.team_id),+ "document_types": ast.Constant(value=document_types),+ "limit": ast.Constant(value=limit),+ }+ if scoped_document_ids is not None:+ where_clauses.append("document_id IN {scoped_document_ids}")+ placeholders["scoped_document_ids"] = ast.Constant(value=scoped_document_ids)++ # The embedding row is used only for ranking and routing. The snippet itself is+ # built from the current Postgres UserInterview field so edits/deletions to the+ # source content are reflected immediately — otherwise an embedding written before+ # an edit would leak the previous text via the search endpoint.+ hogql_query = f"""+ SELECT+ document_id,+ document_type,+ cosineDistance(embedding, {{embedding}}) AS distance+ FROM document_embeddings+ WHERE {" AND ".join(where_clauses)}+ ORDER BY distance ASC+ LIMIT {{limit}}+ """++ tag_queries(product=Product.USER_INTERVIEWS, feature=Feature.SEMANTIC_SEARCH)+ query_result = execute_hogql_query(+ query=hogql_query,+ team=self.team,+ placeholders=placeholders,+ )++ rows = query_result.results or []+ document_ids = {row[0] for row in rows}+ interviews_by_id = {+ str(i.id): i+ for i in UserInterview.objects.filter(team_id=self.team_id, id__in=document_ids).only(+ "id", "interviewee_identifier", "topic_id", "created_at", "transcript", "summary"+ )+ }++ results: list[dict[str, Any]] = []+ for document_id, document_type, distance in rows:+ interview = interviews_by_id.get(document_id)+ if interview is None:+ continue+ live_content = interview.transcript if document_type == "transcript" else interview.summary+ results.append(+ {+ "interview_id": interview.id,+ "document_type": document_type,+ "similarity": min(1.0, max(0.0, 1.0 - float(distance))),+ "content_snippet": (live_content or "")[:SEARCH_CONTENT_SNIPPET_LIMIT],+ "interviewee_identifier": interview.interviewee_identifier,+ "topic_id": interview.topic_id,+ "created_at": interview.created_at,+ }+ )++ return response.Response(UserInterviewSearchResultSerializer(results, many=True).data)+class UserInterviewTopicSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)diff --git a/products/user_interviews/backend/test_search.py b/products/user_interviews/backend/test_search.pynew file mode 100644index 000000000000..4d2ee6aa99e8--- /dev/null+++ b/products/user_interviews/backend/test_search.py@@ -0,0 +1,349 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework import status++from products.user_interviews.backend.models import UserInterview, UserInterviewTopic+++class _FeatureFlagEnabledMixin(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ patcher.start()+ self.addCleanup(patcher.stop)+++class TestUserInterviewSearch(_FeatureFlagEnabledMixin):+ def setUp(self) -> None:+ super().setUp()+ self.topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="Replay adoption",+ agent_context="ctx",+ questions=[],+ )+ self.interview_a = UserInterview.objects.create(+ team=self.team,+ topic=self.topic,+ interviewee_identifier="[email protected]",+ interviewee_emails=["[email protected]"],+ transcript="alex talked about session replay buffering",+ summary="alex finds session replay slow on long sessions",+ created_by=self.user,+ )+ self.interview_b = UserInterview.objects.create(+ team=self.team,+ topic=self.topic,+ interviewee_identifier="[email protected]",+ interviewee_emails=["[email protected]"],+ transcript="bob loves heatmaps but ignores replays",+ summary="bob uses heatmaps daily",+ created_by=self.user,+ )++ def _url(self) -> str:+ return f"/api/environments/{self.team.id}/user_interviews/search/"++ def _embedding_response(self) -> MagicMock:+ resp = MagicMock()+ resp.embedding = [0.0] * 3072+ resp.tokens_used = 4+ resp.did_truncate = False+ return resp++ def _hogql_rows(self, rows: list[tuple[Any, ...]]) -> MagicMock:+ result = MagicMock()+ result.results = rows+ return result++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_returns_ranked_matches(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows(+ [+ (str(self.interview_a.id), "transcript", 0.12),+ (str(self.interview_a.id), "summary", 0.22),+ (str(self.interview_b.id), "transcript", 0.48),+ ]+ )++ response = self.client.post(self._url(), {"query": "is session replay slow?"}, content_type="application/json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)++ body = response.json()+ self.assertEqual(len(body), 3)+ self.assertEqual(body[0]["interview_id"], str(self.interview_a.id))+ self.assertEqual(body[0]["document_type"], "transcript")+ self.assertAlmostEqual(body[0]["similarity"], 0.88, places=5)+ self.assertEqual(body[0]["content_snippet"], "alex talked about session replay buffering")+ self.assertEqual(body[0]["interviewee_identifier"], "[email protected]")+ self.assertEqual(body[0]["topic_id"], str(self.topic.id))+ self.assertGreater(body[0]["similarity"], body[2]["similarity"])++ mock_embed.assert_called_once()+ embed_args, embed_kwargs = mock_embed.call_args+ self.assertEqual(embed_args[0], self.team)+ self.assertEqual(embed_args[1], "is session replay slow?")+ self.assertEqual(embed_kwargs["model"], "text-embedding-3-large-3072")++ @parameterized.expand(+ [+ ("distance_above_one_clamps_to_zero", 1.4, 0.0),+ ("negative_distance_clamps_to_one", -0.01, 1.0),+ ]+ )+ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_clamps_similarity_to_unit_interval(self, _name, distance, expected, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", distance)])+ response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()[0]["similarity"], expected)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_snippet_reflects_current_postgres_content(self, mock_embed, mock_hogql):+ """The snippet must come from the live UserInterview row, not the embedding row's+ snapshot — otherwise editing or trimming a transcript leaves stale content visible+ through the search endpoint until the embedding ages out."""+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", 0.1)])++ self.interview_a.transcript = "alex's edited transcript: replay is faster now"+ self.interview_a.save(update_fields=["transcript"])++ response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")+ self.assertEqual(response.json()[0]["content_snippet"], "alex's edited transcript: replay is faster now")++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_truncates_long_content_snippet(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ self.interview_a.transcript = "x" * 1000+ self.interview_a.save(update_fields=["transcript"])+ mock_hogql.return_value = self._hogql_rows([(str(self.interview_a.id), "transcript", 0.1)])+ response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")+ self.assertEqual(len(response.json()[0]["content_snippet"]), 500)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_skips_rows_for_deleted_interviews(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ ghost_id = "00000000-0000-0000-0000-000000000000"+ mock_hogql.return_value = self._hogql_rows(+ [+ (str(self.interview_a.id), "transcript", 0.1),+ (ghost_id, "transcript", 0.2),+ ]+ )+ response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")+ body = response.json()+ self.assertEqual(len(body), 1)+ self.assertEqual(body[0]["interview_id"], str(self.interview_a.id))++ @parameterized.expand(+ [+ ("transcript_only", ["transcript"], {"transcript"}),+ ("summary_only", ["summary"], {"summary"}),+ ("both_explicit", ["transcript", "summary"], {"transcript", "summary"}),+ ]+ )+ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_forwards_document_types_filter(+ self, _name, document_types, expected_in_placeholders, mock_embed, mock_hogql+ ):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(+ self._url(),+ {"query": "x", "document_types": document_types},+ content_type="application/json",+ )++ mock_hogql.assert_called_once()+ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(set(placeholders["document_types"].value), expected_in_placeholders)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_resolves_topic_id_via_current_postgres_linkage(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(+ self._url(),+ {"query": "x", "topic_id": str(self.topic.id)},+ content_type="application/json",+ )++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ # Both seeded interviews are currently linked to the topic; the search WHERE clause+ # is built from that *current* linkage, not from the embedding-time metadata snapshot.+ self.assertEqual(+ set(placeholders["scoped_document_ids"].value),+ {str(self.interview_a.id), str(self.interview_b.id)},+ )+ hogql_query = mock_hogql.call_args.kwargs["query"]+ self.assertIn("document_id IN {scoped_document_ids}", hogql_query)+ self.assertNotIn("JSONExtractString(metadata, 'topic_id')", hogql_query)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_excludes_interviews_detached_from_topic(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])+ # Detach interview_b from the topic — its embedding row still names topic in metadata,+ # but the Postgres linkage is gone, so it must NOT appear in the scoped id set.+ self.interview_b.topic = None+ self.interview_b.save(update_fields=["topic"])++ self.client.post(+ self._url(),+ {"query": "x", "topic_id": str(self.topic.id)},+ content_type="application/json",+ )++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(set(placeholders["scoped_document_ids"].value), {str(self.interview_a.id)})++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_short_circuits_when_topic_has_no_interviews(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ # No call to HogQL should happen when the topic resolves to zero interview IDs.+ empty_topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="No interviews yet",+ agent_context="",+ questions=[],+ )++ response = self.client.post(+ self._url(),+ {"query": "x", "topic_id": str(empty_topic.id)},+ content_type="application/json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])+ mock_hogql.assert_not_called()+ mock_embed.assert_not_called()++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_defaults_to_both_document_types_when_unset(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(self._url(), {"query": "x"}, content_type="application/json")++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(set(placeholders["document_types"].value), {"transcript", "summary"})++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_enforces_default_limit_when_omitted(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(self._url(), {"query": "x"}, content_type="application/json")++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(placeholders["limit"].value, 10)++ @parameterized.expand(+ [+ ("missing_query", {}),+ ("query_above_max_length", {"query": "x" * 2001}),+ ("limit_above_max", {"query": "x", "limit": 51}),+ ("invalid_document_type", {"query": "x", "document_types": ["nonsense"]}),+ ("empty_document_types_list", {"query": "x", "document_types": []}),+ ]+ )+ def test_search_rejects_invalid_request(self, _name, payload):+ response = self.client.post(self._url(), payload, content_type="application/json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_search_action_declares_read_scope(self):+ from products.user_interviews.backend.api import UserInterviewViewSet++ self.assertEqual(UserInterviewViewSet.search.kwargs["required_scopes"], ["user_interview:read"])++ @patch("products.user_interviews.backend.api.tag_queries")+ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_tags_clickhouse_query_for_attribution(self, mock_embed, mock_hogql, mock_tag):+ from posthog.clickhouse.query_tagging import Feature, Product++ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(self._url(), {"query": "x"}, content_type="application/json")++ mock_tag.assert_called_once_with(product=Product.USER_INTERVIEWS, feature=Feature.SEMANTIC_SEARCH)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch(+ "products.user_interviews.backend.api.generate_embedding",+ side_effect=RuntimeError("embedding service down"),+ )+ def test_search_returns_502_when_embedding_service_fails(self, _mock_embed, mock_hogql):+ response = self.client.post(self._url(), {"query": "x"}, content_type="application/json")+ self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)+ self.assertIn("Embedding service", response.json()["detail"])+ mock_hogql.assert_not_called()++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_caps_scoped_document_ids_for_pathological_topic_size(self, mock_embed, mock_hogql):+ from products.user_interviews.backend.api import SEARCH_TOPIC_INTERVIEW_CAP++ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])+ # Create enough interviews to exceed the cap. Generate them in a single batch.+ UserInterview.objects.bulk_create(+ [+ UserInterview(+ team=self.team,+ topic=self.topic,+ interviewee_identifier=f"person-{i}@example.com",+ interviewee_emails=[f"person-{i}@example.com"],+ transcript="t",+ summary="s",+ created_by=self.user,+ )+ for i in range(SEARCH_TOPIC_INTERVIEW_CAP + 5)+ ]+ )++ self.client.post(+ self._url(),+ {"query": "x", "topic_id": str(self.topic.id)},+ content_type="application/json",+ )++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(len(placeholders["scoped_document_ids"].value), SEARCH_TOPIC_INTERVIEW_CAP)++ @patch("products.user_interviews.backend.api.execute_hogql_query")+ @patch("products.user_interviews.backend.api.generate_embedding")+ def test_search_does_not_leak_across_teams(self, mock_embed, mock_hogql):+ mock_embed.return_value = self._embedding_response()+ mock_hogql.return_value = self._hogql_rows([])++ self.client.post(self._url(), {"query": "x"}, content_type="application/json")++ placeholders = mock_hogql.call_args.kwargs["placeholders"]+ self.assertEqual(placeholders["team_id"].value, self.team.id)diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.tsindex 092ad0af90e1..492138770ba9 100644--- a/products/user_interviews/frontend/generated/api.schemas.ts+++ b/products/user_interviews/frontend/generated/api.schemas.ts@@ -239,6 +239,65 @@ export interface PatchedUserInterviewApi {audio?: string}+/**+ * * `transcript` - transcript+ * `summary` - summary+ */+export type UserInterviewSearchDocumentTypeEnumApi =+ (typeof UserInterviewSearchDocumentTypeEnumApi)[keyof typeof UserInterviewSearchDocumentTypeEnumApi]++export const UserInterviewSearchDocumentTypeEnumApi = {+ Transcript: 'transcript',+ Summary: 'summary',+} as const++export interface UserInterviewSearchRequestApi {+ /**+ * Natural-language query to match semantically against interview transcripts and summaries.+ * @maxLength 2000+ */+ query: string+ /**+ * Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.+ * @minItems 1+ */+ document_types?: UserInterviewSearchDocumentTypeEnumApi[]+ /**+ * Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.+ * @nullable+ */+ topic_id?: string | null+ /**+ * Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.+ * @minimum 1+ * @maximum 50+ */+ limit?: number+}++export interface UserInterviewSearchResultApi {+ /** ID of the matched UserInterview. */+ interview_id: string+ /** Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.++ * `transcript` - transcript+ * `summary` - summary */+ document_type: UserInterviewSearchDocumentTypeEnumApi+ /** Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`. */+ similarity: number+ /** Excerpt of the matched document (first 500 characters). */+ content_snippet: string+ /** Email or PostHog distinct ID of the interviewee. */+ interviewee_identifier: string+ /**+ * ID of the UserInterviewTopic the interview was conducted for, or null if detached.+ * @nullable+ */+ topic_id: string | null+ /** When the interview row was created. */+ created_at: string+}+export type UserInterviewTopicsListParams = {/*** Number of results to return per page.diff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.tsindex 36f6d2c57a3e..ba037fa26e45 100644--- a/products/user_interviews/frontend/generated/api.ts+++ b/products/user_interviews/frontend/generated/api.ts@@ -20,6 +20,8 @@ import type {PatchedUserInterviewTopicApi,SendInvitesRequestApi,UserInterviewApi,+ UserInterviewSearchRequestApi,+ UserInterviewSearchResultApi,UserInterviewTopicApi,UserInterviewTopicsIntervieweesListParams,UserInterviewTopicsListParams,@@ -488,3 +490,24 @@ export const userInterviewsDestroy = async (projectId: string, id: string, optiomethod: 'DELETE',})}++export const getUserInterviewsSearchCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/user_interviews/search/`+}++/**+ * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.+ * @summary Search interview responses by semantic similarity+ */+export const userInterviewsSearchCreate = async (+ projectId: string,+ userInterviewSearchRequestApi: UserInterviewSearchRequestApi,+ options?: RequestInit+): Promise<UserInterviewSearchResultApi[]> => {+ return apiMutator<UserInterviewSearchResultApi[]>(getUserInterviewsSearchCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(userInterviewSearchRequestApi),+ })+}diff --git a/products/user_interviews/frontend/generated/api.zod.ts b/products/user_interviews/frontend/generated/api.zod.tsindex 941fd99f8270..e53969e133e5 100644--- a/products/user_interviews/frontend/generated/api.zod.ts+++ b/products/user_interviews/frontend/generated/api.zod.ts@@ -206,3 +206,37 @@ export const UserInterviewsPartialUpdateBody = /* @__PURE__ */ zod.object({summary: zod.string().optional(),audio: zod.url().optional(),})++/**+ * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.+ * @summary Search interview responses by semantic similarity+ */+export const userInterviewsSearchCreateBodyQueryMax = 2000++export const userInterviewsSearchCreateBodyLimitMax = 50++export const UserInterviewsSearchCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .string()+ .max(userInterviewsSearchCreateBodyQueryMax)+ .describe('Natural-language query to match semantically against interview transcripts and summaries.'),+ document_types: zod+ .array(zod.enum(['transcript', 'summary']).describe('\* `transcript` - transcript\n\* `summary` - summary'))+ .min(1)+ .optional()+ .describe(+ 'Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.'+ ),+ topic_id: zod+ .uuid()+ .nullish()+ .describe('Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.'),+ limit: zod+ .number()+ .min(1)+ .max(userInterviewsSearchCreateBodyLimitMax)+ .optional()+ .describe(+ 'Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.'+ ),+})diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yamlindex 8fb3c7180f49..2629f96c6b17 100644--- a/products/user_interviews/mcp/tools.yaml+++ b/products/user_interviews/mcp/tools.yaml@@ -192,6 +192,25 @@ tools:`summary`. Use after `user-interviews-list` has narrowed down to a specific interview — for example, to readwhat a particular interviewee said about a research topic.feature_flag: user-interviews+ user-interviews-search:+ operation: user_interviews_search_create+ enabled: true+ scopes:+ - user_interview:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Semantic search across interview responses+ description: >+ Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same+ model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match+ is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and+ summary score above other interviews. Use `document_types` to restrict to just `transcript` or just+ `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of+ returned matches (1-50, default 10). Useful for surfacing relevant excerpts when the caller has a research+ question rather than a known string to grep for.+ feature_flag: user-interviewsuser-interviews-update:operation: user_interviews_updateenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6d0bccba4044..7f43d4fb83c5 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4870,6 +4870,22 @@},"feature_flag": "user-interviews"},+ "user-interviews-search": {+ "description": "Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Use `document_types` to restrict to just `transcript` or just `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of returned matches (1-50, default 10). Useful for surfacing relevant excerpts when the caller has a research question rather than a known string to grep for.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Semantic search across interview responses",+ "title": "Semantic search across interview responses",+ "required_scopes": ["user_interview:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "user-interviews"+ },"user-settings-update": {"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.","category": "Core",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f086170c155d..31325ca0b9a5 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5351,6 +5351,22 @@},"feature_flag": "user-interviews"},+ "user-interviews-search": {+ "description": "Search recorded user interviews by meaning, not keywords. Embeds the natural-language `query` with the same model used to index transcripts and summaries, then returns the top matches by cosine similarity. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Use `document_types` to restrict to just `transcript` or just `summary`. Filter by `topic_id` to scope the search to a single interview topic. `limit` caps the number of returned matches (1-50, default 10). Useful for surfacing relevant excerpts when the caller has a research question rather than a known string to grep for.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Semantic search across interview responses",+ "title": "Semantic search across interview responses",+ "required_scopes": ["user_interview:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "user-interviews"+ },"user-settings-update": {"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.","category": "Core",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7ce081874f4d..b275139b459a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8039,10 +8039,10 @@ export namespace Schemas {* * `BAA` - BAA* `DPA` - DPA*/- export type DocumentTypeEnum = typeof DocumentTypeEnum[keyof typeof DocumentTypeEnum];+ export type CreateLegalDocumentDocumentTypeEnum = typeof CreateLegalDocumentDocumentTypeEnum[keyof typeof CreateLegalDocumentDocumentTypeEnum];- export const DocumentTypeEnum = {+ export const CreateLegalDocumentDocumentTypeEnum = {Baa: 'BAA',Dpa: 'DPA',} as const;@@ -8057,7 +8057,7 @@ export namespace Schemas {* `BAA` - BAA* `DPA` - DPA */- document_type: DocumentTypeEnum;+ document_type: CreateLegalDocumentDocumentTypeEnum;/*** The customer legal entity entering the agreement (PandaDoc's Client.Company).* @maxLength 255@@ -35597,6 +35597,65 @@ export namespace Schemas {connect_flow: string;}+ /**+ * * `transcript` - transcript+ * `summary` - summary+ */+ export type UserInterviewSearchDocumentTypeEnum = typeof UserInterviewSearchDocumentTypeEnum[keyof typeof UserInterviewSearchDocumentTypeEnum];+++ export const UserInterviewSearchDocumentTypeEnum = {+ Transcript: 'transcript',+ Summary: 'summary',+ } as const;++ export interface UserInterviewSearchRequest {+ /**+ * Natural-language query to match semantically against interview transcripts and summaries.+ * @maxLength 2000+ */+ query: string;+ /**+ * Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.+ * @minItems 1+ */+ document_types?: UserInterviewSearchDocumentTypeEnum[];+ /**+ * Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.+ * @nullable+ */+ topic_id?: string | null;+ /**+ * Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.+ * @minimum 1+ * @maximum 50+ */+ limit?: number;+ }++ export interface UserInterviewSearchResult {+ /** ID of the matched UserInterview. */+ interview_id: string;+ /** Which document type matched — `transcript` is the raw conversation, `summary` is the AI-generated abstract.++ * `transcript` - transcript+ * `summary` - summary */+ document_type: UserInterviewSearchDocumentTypeEnum;+ /** Cosine similarity in [0, 1]; higher is closer to the query. Computed as `1 - cosineDistance`. */+ similarity: number;+ /** Excerpt of the matched document (first 500 characters). */+ content_snippet: string;+ /** Email or PostHog distinct ID of the interviewee. */+ interviewee_identifier: string;+ /**+ * ID of the UserInterviewTopic the interview was conducted for, or null if detached.+ * @nullable+ */+ topic_id: string | null;+ /** When the interview row was created. */+ created_at: string;+ }+export interface UserPushTokenItem {/** PostHog UserPushToken row id. */id: string;diff --git a/services/mcp/src/generated/user_interviews/api.ts b/services/mcp/src/generated/user_interviews/api.tsindex a4be5eea29fa..a07c6b99e192 100644--- a/services/mcp/src/generated/user_interviews/api.ts+++ b/services/mcp/src/generated/user_interviews/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 8 enabled ops+ * PostHog API - MCP 9 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -176,3 +176,45 @@ export const UserInterviewsRetrieveParams = /* @__PURE__ */ zod.object({"Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."),})++/**+ * Embed `query` with the same model used to index interview transcripts and summaries, then return the top matches by cosine distance. Each match is a single (interview, document_type) pair — an interview can appear up to twice if both its transcript and summary score above other interviews. Useful for surfacing relevant interview snippets in natural language, without exact keyword matches.+ * @summary Search interview responses by semantic similarity+ */+export const UserInterviewsSearchCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const userInterviewsSearchCreateBodyQueryMax = 2000++export const userInterviewsSearchCreateBodyLimitMax = 50++export const UserInterviewsSearchCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .string()+ .max(userInterviewsSearchCreateBodyQueryMax)+ .describe('Natural-language query to match semantically against interview transcripts and summaries.'),+ document_types: zod+ .array(zod.enum(['transcript', 'summary']).describe('* `transcript` - transcript\n* `summary` - summary'))+ .min(1)+ .optional()+ .describe(+ 'Which document types to search across. Omit to default to both `transcript` and `summary`. Pass a non-empty subset to restrict the search.'+ ),+ topic_id: zod+ .uuid()+ .nullish()+ .describe('Optional. Restrict results to interviews belonging to a specific UserInterviewTopic.'),+ limit: zod+ .number()+ .min(1)+ .max(userInterviewsSearchCreateBodyLimitMax)+ .optional()+ .describe(+ 'Maximum number of matches to return (1-50). Defaults to 10. Two matches per interview are possible — one for the transcript, one for the summary.'+ ),+})diff --git a/services/mcp/src/tools/generated/user_interviews.ts b/services/mcp/src/tools/generated/user_interviews.tsindex 595523e35a7e..f067bf38f693 100644--- a/services/mcp/src/tools/generated/user_interviews.ts+++ b/services/mcp/src/tools/generated/user_interviews.ts@@ -14,6 +14,7 @@ import {UserInterviewTopicsSendInvitesCreateParams,UserInterviewsListQueryParams,UserInterviewsRetrieveParams,+ UserInterviewsSearchCreateBody,} from '@/generated/user_interviews/api'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -212,6 +213,35 @@ const userInterviewsRetrieve = (): ToolBase<typeof UserInterviewsRetrieveSchema,},})+const UserInterviewsSearchSchema = UserInterviewsSearchCreateBody++const userInterviewsSearch = (): ToolBase<typeof UserInterviewsSearchSchema, Schemas.UserInterviewSearchResult[]> => ({+ name: 'user-interviews-search',+ schema: UserInterviewsSearchSchema,+ handler: async (context: Context, params: z.infer<typeof UserInterviewsSearchSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.query !== undefined) {+ body['query'] = params.query+ }+ if (params.document_types !== undefined) {+ body['document_types'] = params.document_types+ }+ if (params.topic_id !== undefined) {+ body['topic_id'] = params.topic_id+ }+ if (params.limit !== undefined) {+ body['limit'] = params.limit+ }+ const result = await context.api.request<Schemas.UserInterviewSearchResult[]>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interviews/search/`,+ body,+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'user-interview-topics-create': userInterviewTopicsCreate,'user-interview-topics-generate-links': userInterviewTopicsGenerateLinks,@@ -221,4 +251,5 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'user-interview-topics-send-invites': userInterviewTopicsSendInvites,'user-interviews-list': userInterviewsList,'user-interviews-retrieve': userInterviewsRetrieve,+ 'user-interviews-search': userInterviewsSearch,}