: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(taxonomic-filter): suggest the right tab for a picker search (#106531)
Paul D'Ambra6bf90a57a2f2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 68fcb0fbaddb..fe758b4998f0 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3192,6 +3192,22 @@ snapshots:hash: v1.k794b7964.7a64d4e031d99774addf09c78809b732e1de363b31f9c700218c8bf7575d3e2f.bm9u1TaKULFXL7zhr293AHvC82-5Puiypn88v0euEJUfilters-taxonomic-filter--renamed-series-selected-with-all-results--light:hash: v1.k794b7964.1940698d5a4fcf5314afcc4f2f582228c3adcf8d8b7cc5f8725441f8a8d040b6.L87TGLih84ffADwLJZCeToQdaIewW50aBiH7MdbZ1CQ+ filters-taxonomic-filter--search-intent-control-keeps-order--dark:+ hash: v1.k794b7964.a697849cb795fb3b6831e77c4473f44b731cd37bf3c95fc2e222860ec8fbfc99.PYkSY0kqft5THgGC8cU6kc3FBsEI445P6wJiKTUKhi4+ filters-taxonomic-filter--search-intent-control-keeps-order--light:+ hash: v1.k794b7964.37b41323e066412ea5791d7139276a8511a214eab9560e688f059a58a26f4fed.0oJtl5BM6R1utvMNfrefc-Hz5Jj785IOLbcsoAoKin0+ filters-taxonomic-filter--search-intent-promotes-group--dark:+ hash: v1.k794b7964.36bfca465fa81a617cb228956bf5cbcbdfc742b8010f455688310ea35a353a67.EDotXLAmxjeQbl7CmhNRK8ItX_qcXIBHu938KCKvUS8+ filters-taxonomic-filter--search-intent-promotes-group--light:+ hash: v1.k794b7964.83f80eea84d432f02d4805fccf7d4bdd36b9c853ae5f3d1457a6ae5085dc7364.z_EjK_5yHgfoXb-ZhW_vyfIADr3-zmcB95BsN_J7kMM+ filters-taxonomic-filter--search-intent-suggests-another-tab--dark:+ hash: v1.k794b7964.61581a9d1a554763f3f3b9e75c589c2e8381ec0b095ab01c3be710d1633fb39a.7oLeqOE7IrAcIczEzfyz-Q3xA4f-bUNUVEtLOqYmwnU+ filters-taxonomic-filter--search-intent-suggests-another-tab--light:+ hash: v1.k794b7964.95b498302f181db07c6d8be5528c74d14a6ed6d0cbc2dc0ee63ecbbc24a8117e.2CjYTZMA0k6oczwSYqMQ7n9U6zak9bZzMI9hBy5IasI+ filters-taxonomic-filter--search-intent-suggests-another-tab-narrow--dark:+ hash: v1.k794b7964.e62e0423c458e5bf70b071a30b18a50500e10878891f69698707b79cacfb8110.JB3_vSta_2QaPMROCj08V7BF0312G-z9WuaSlQ9OH7c+ filters-taxonomic-filter--search-intent-suggests-another-tab-narrow--light:+ hash: v1.k794b7964.72234524ecda0b8294d10f45c644bf92f87bd593c0b7302a9de4e28ebadd1540.rNOcJTlCEBkSlMS7HKGL16EFcy-zV4nysz_uUxeWNm8filters-taxonomic-filter--six-groups-default-layout--dark:hash: v1.k794b7964.627294fb84ded4e91c4b583e04c2b6e9ca0bdcd34464f49d0d26234cc89d4348.M68XdlTkoApLdDr13jO67fmlGFLjATJfb8ZwdU6xP5Yfilters-taxonomic-filter--six-groups-default-layout--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 9885b11497dc..f4711304f302 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4357,6 +4357,69 @@ export interface BulkUpdateTagsResponseApi {skipped: BulkUpdateTagsErrorApi[]}+export interface SearchIntentRequestApi {+ /**+ * What the person typed into the filter picker search box.+ * @maxLength 200+ */+ query: string+ /**+ * The picker tab that is open, as a taxonomic group type such as event_properties.+ * @maxLength 100+ */+ active_group_type: string+ /**+ * The taxonomic group types the picker shows. The answer is always one of these, or null.+ * @maxItems 64+ * @items.maxLength 100+ */+ available_group_types: string[]+ /**+ * The id of the scene the picker is open in, such as Insight or Replay.+ * @nullable+ * @pattern ^[A-Za-z0-9_-]{1,64}$+ */+ scene?: string | null+}++/**+ * * `rule` - Matched a value pattern+ * * `model` - Asked the decision model+ * * `skipped` - Not classified+ */+export type SearchIntentSourceEnumApi = (typeof SearchIntentSourceEnumApi)[keyof typeof SearchIntentSourceEnumApi]++export const SearchIntentSourceEnumApi = {+ Rule: 'rule',+ Model: 'model',+ Skipped: 'skipped',+} as const++export interface SearchIntentResponseApi {+ /**+ * The taxonomic group type the search most likely belongs to, or null if it was not classified.+ * @nullable+ */+ group_type: string | null+ /** How far the chosen group stands out from the rest, from 0 (a coin flip) to 1. */+ confidence: number+ /** Whether the confidence is high enough to act on, for example to suggest a different tab. */+ is_confident: boolean+ /** Whether the picker should suggest switching from the open tab to group_type. */+ suggests_switch: boolean+ /** How the answer was found: a value pattern, the decision model, or not at all.+ *+ * * `rule` - Matched a value pattern+ * * `model` - Asked the decision model+ * * `skipped` - Not classified */+ method: SearchIntentSourceEnumApi+ /**+ * The version of the managed search intent prompt the model read. Null for a value pattern, a skipped search, or the bundled fallback prompt.+ * @nullable+ */+ prompt_version: number | null+}+export interface UploadedMediaApi {readonly id: string/** The file's original name. */diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 5c82965e88e1..dda59fa1b473 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -88,6 +88,8 @@ import type {PropertyDefinitionsListParams,RevokeOtherSessionsResponseApi,SCIMTokenResponseApi,+ SearchIntentRequestApi,+ SearchIntentResponseApi,SharingConfigurationApi,ToolbarEntitlementsApi,TwoFactorStatusApi,@@ -2546,6 +2548,27 @@ export const sessionRecordingsSharingRefreshCreate = async (})}+export const getTaxonomicSearchIntentClassifyCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/taxonomic_search_intent/classify/`+}++/**+ * Guess which filter picker tab a search belongs to, so the picker can suggest or promote it.+ * @summary Classify a filter picker search+ */+export const taxonomicSearchIntentClassifyCreate = async (+ projectId: string,+ searchIntentRequestApi: SearchIntentRequestApi,+ options?: RequestInit+): Promise<SearchIntentResponseApi> => {+ return apiMutator<SearchIntentResponseApi>(getTaxonomicSearchIntentClassifyCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(searchIntentRequestApi),+ })+}+export const getUploadedMediaListUrl = (projectId: string, params: UploadedMediaListParams) => {const normalizedParams = new URLSearchParams()diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 3539b1df5218..5e38148882ed 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -1136,6 +1136,40 @@ export const SessionRecordingsSharingRefreshCreateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+/**+ * Guess which filter picker tab a search belongs to, so the picker can suggest or promote it.+ * @summary Classify a filter picker search+ */+export const taxonomicSearchIntentClassifyCreateBodyQueryMax = 200++export const taxonomicSearchIntentClassifyCreateBodyActiveGroupTypeMax = 100++export const taxonomicSearchIntentClassifyCreateBodyAvailableGroupTypesItemMax = 100++export const taxonomicSearchIntentClassifyCreateBodyAvailableGroupTypesMax = 64++export const taxonomicSearchIntentClassifyCreateBodySceneRegExp = new RegExp('^[A-Za-z0-9_-]{1,64}$')++export const TaxonomicSearchIntentClassifyCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .string()+ .max(taxonomicSearchIntentClassifyCreateBodyQueryMax)+ .describe('What the person typed into the filter picker search box.'),+ active_group_type: zod+ .string()+ .max(taxonomicSearchIntentClassifyCreateBodyActiveGroupTypeMax)+ .describe('The picker tab that is open, as a taxonomic group type such as event_properties.'),+ available_group_types: zod+ .array(zod.string().max(taxonomicSearchIntentClassifyCreateBodyAvailableGroupTypesItemMax))+ .max(taxonomicSearchIntentClassifyCreateBodyAvailableGroupTypesMax)+ .describe('The taxonomic group types the picker shows. The answer is always one of these, or null.'),+ scene: zod+ .string()+ .regex(taxonomicSearchIntentClassifyCreateBodySceneRegExp)+ .nullish()+ .describe('The id of the scene the picker is open in, such as Insight or Replay.'),+})+/**** When object storage is available this API allows upload of media which can be used, for example, in text cards on dashboards.diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsxindex 68e56d768e8d..86751ebc110e 100644--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx@@ -845,3 +845,97 @@ export const EmptyEventsWithStaleToggle: Story = {},},}++// The decision model answers "person properties" for a search of "email" in every search intent story.+const searchIntentPersonPropertiesMock = mswDecorator({+ post: {+ '/api/projects/:team_id/taxonomic_search_intent/classify/': () => [+ 200,+ {+ group_type: 'person_properties',+ confidence: 0.9,+ is_confident: true,+ suggests_switch: true,+ method: 'model',+ },+ ],+ },+})++const SEARCH_INTENT_GROUP_TYPES = [+ TaxonomicFilterGroupType.SuggestedFilters,+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.SessionProperties,+]++function SearchIntentStoryRender({+ args,+ tab,+}: {+ args: TaxonomicFilterProps+ tab: TaxonomicFilterGroupType+}): JSX.Element {+ const logicKey = args.taxonomicFilterLogicKey as string+ const { setActiveTab, setSearchQuery } = useActions(+ taxonomicFilterLogic({ ...args, taxonomicFilterLogicKey: logicKey })+ )+ useOnMountEffect(() => {+ setActiveTab(tab)+ setSearchQuery('email')+ })+ return (+ <div className="w-fit border rounded p-2 bg-surface-primary">+ <TaxonomicFilter {...args} />+ </div>+ )+}++/** Banner arm: a search that belongs in another tab gets a suggestion to switch to it. */+export const SearchIntentSuggestsAnotherTab: Story = {+ render: (args) => <SearchIntentStoryRender args={args} tab={TaxonomicFilterGroupType.EventProperties} />,+ args: { taxonomicFilterLogicKey: 'search-intent-banner', taxonomicGroupTypes: SEARCH_INTENT_GROUP_TYPES },+ decorators: [searchIntentPersonPropertiesMock],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'banner' },+ testOptions: { waitForSelector: '[data-attr="taxonomic-search-intent-switch"]' },+ },+}++/** Banner arm in a narrow scene: the switch button stacks under the question. */+export const SearchIntentSuggestsAnotherTabNarrow: Story = {+ render: (args) => <SearchIntentStoryRender args={args} tab={TaxonomicFilterGroupType.EventProperties} />,+ args: {+ taxonomicFilterLogicKey: 'search-intent-banner-narrow',+ taxonomicGroupTypes: SEARCH_INTENT_GROUP_TYPES,+ width: 360,+ },+ decorators: [searchIntentPersonPropertiesMock],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'banner' },+ // LemonBanner renders the action twice and hides the wide copy at this width, so wait for the narrow copy.+ testOptions: { waitForSelector: '[data-attr="taxonomic-search-intent-switch"].LemonButton--full-width' },+ },+}++/** Control arm: the same answer arrives, and the "All" list keeps its usual group order. */+export const SearchIntentControlKeepsOrder: Story = {+ render: (args) => <SearchIntentStoryRender args={args} tab={TaxonomicFilterGroupType.SuggestedFilters} />,+ args: { taxonomicFilterLogicKey: 'search-intent-control', taxonomicGroupTypes: SEARCH_INTENT_GROUP_TYPES },+ decorators: [searchIntentPersonPropertiesMock],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'control' },+ testOptions: { waitForSelector: '.taxonomic-infinite-list' },+ },+}++/** Promote arm: the predicted group moves to the top of the "All" list before the results show. */+export const SearchIntentPromotesGroup: Story = {+ render: (args) => <SearchIntentStoryRender args={args} tab={TaxonomicFilterGroupType.SuggestedFilters} />,+ args: { taxonomicFilterLogicKey: 'search-intent-promote', taxonomicGroupTypes: SEARCH_INTENT_GROUP_TYPES },+ decorators: [searchIntentPersonPropertiesMock],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'promote' },+ testOptions: { waitForSelector: '.taxonomic-infinite-list' },+ },+}diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsxindex 0a5b12b44be6..d84cb3935b25 100644--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.tsx@@ -19,6 +19,7 @@ import { urls } from 'scenes/urls'import { CategoryDropdown } from './CategoryDropdown'import { InfiniteSelectResults } from './InfiniteSelectResults'import { defaultDataWarehousePopoverFields, taxonomicFilterLogic } from './taxonomicFilterLogic'+import { TaxonomicSearchIntentBanner } from './TaxonomicSearchIntentBanner'export function TaxonomicFilter({taxonomicFilterLogicKey: taxonomicFilterLogicKeyInput,@@ -156,6 +157,7 @@ export function TaxonomicFilter({eventName={eventNames?.[0]}focusInput={focusInput}/>+ <TaxonomicSearchIntentBanner taxonomicFilterLogicProps={taxonomicFilterLogicProps} /></div>) : null}{refReady && (diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicSearchIntentBanner.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicSearchIntentBanner.tsxnew file mode 100644index 000000000000..a703ad4abc72--- /dev/null+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicSearchIntentBanner.tsx@@ -0,0 +1,40 @@+import { useActions, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'++import { taxonomicSearchIntentLogic } from './taxonomicSearchIntentLogic'+import { TaxonomicFilterLogicProps } from './types'++function lowercaseFirst(text: string): string {+ return text.charAt(0).toLowerCase() + text.slice(1)+}++export function TaxonomicSearchIntentBanner({+ taxonomicFilterLogicProps,+}: {+ taxonomicFilterLogicProps: TaxonomicFilterLogicProps+}): JSX.Element | null {+ const logic = taxonomicSearchIntentLogic(taxonomicFilterLogicProps)+ const { suggestedSwitch } = useValues(logic)+ const { acceptSuggestedSwitch } = useActions(logic)++ if (!suggestedSwitch) {+ return null+ }++ return (+ <LemonBanner+ type="info"+ className="mt-1"+ hideIcon+ action={{+ children: `Switch to ${lowercaseFirst(suggestedSwitch.groupName)}`,+ onClick: acceptSuggestedSwitch,+ // pinned: data-attr, autocapture and the experiment read it+ 'data-attr': 'taxonomic-search-intent-switch',+ }}+ >+ Looking for {lowercaseFirst(suggestedSwitch.groupName)}?+ </LemonBanner>+ )+}diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsxindex 1830e110fb9f..20f148c9da24 100644--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.tsx@@ -554,6 +554,7 @@ export interface taxonomicFilterLogicValues {infiniteListResultCounts: {[k: string]: number}+ intentPromotedGroupType: TaxonomicFilterGroupType | nullloadingGroupTypes: TaxonomicFilterGroupType[]maxContextOptions: anymetaGroupTypes: Set<string>@@ -649,6 +650,9 @@ export interface taxonomicFilterLogicActions {setIncludeStaleEvents: (includeStaleEvents: boolean) => {includeStaleEvents: boolean}+ setIntentPromotedGroupType: (groupType: TaxonomicFilterGroupType | null) => {+ groupType: TaxonomicFilterGroupType | null+ }setSearchQuery: (searchQuery: string) => {searchQuery: string}@@ -805,7 +809,8 @@ export interface taxonomicFilterLogicMeta {) => stringsuggestedFilterGroupOrder: (taxonomicGroupTypes: TaxonomicFilterGroupType[],- metaGroupTypes: Set<string>+ metaGroupTypes: Set<string>,+ intentPromotedGroupType: TaxonomicFilterGroupType | null) => TaxonomicFilterGroupType[]redistributedTopMatchItems: (topMatchItems: (TaxonomicDefinitionTypes & {@@ -893,6 +898,7 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([}),openRevealBarrier: true,setIncludeStaleEvents: (includeStaleEvents: boolean) => ({ includeStaleEvents }),+ setIntentPromotedGroupType: (groupType: TaxonomicFilterGroupType | null) => ({ groupType }),})),reducers(({ props }) => ({searchQuery: [@@ -977,6 +983,15 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([setActiveTab: () => false,},],+ intentPromotedGroupType: [+ // Set by taxonomicSearchIntentLogic in the promote arm of its experiment. Every new+ // search clears it, so a promotion never outlives the search it was made for.+ null as TaxonomicFilterGroupType | null,+ {+ setIntentPromotedGroupType: (_, { groupType }) => groupType,+ setSearchQuery: () => null,+ },+ ],})),selectors({selectedItemMeta: [() => [(_, props) => props.filter], (filter) => filter],@@ -2464,12 +2479,18 @@ export const taxonomicFilterLogic = kea<taxonomicFilterLogicType>([suggestedFilterGroupOrder: [// The order the cross-category "All" list renders its groups in. Every consumer of that// list must read this, so the skeleton rows and the revealed rows land in the same place.- (s) => [s.taxonomicGroupTypes, s.metaGroupTypes],+ (s) => [s.taxonomicGroupTypes, s.metaGroupTypes, s.intentPromotedGroupType],(taxonomicGroupTypes: TaxonomicFilterGroupType[],- metaGroupTypes: Set<string>- ): TaxonomicFilterGroupType[] =>- demoteValueShortcutGroups(taxonomicGroupTypes.filter((t) => !metaGroupTypes.has(t))),+ metaGroupTypes: Set<string>,+ intentPromotedGroupType: TaxonomicFilterGroupType | null+ ): TaxonomicFilterGroupType[] => {+ const order = demoteValueShortcutGroups(taxonomicGroupTypes.filter((t) => !metaGroupTypes.has(t)))+ if (!intentPromotedGroupType || !order.includes(intentPromotedGroupType)) {+ return order+ }+ return [intentPromotedGroupType, ...order.filter((t) => t !== intentPromotedGroupType)]+ },],redistributedTopMatchItems: [(s) => [s.topMatchItems, s.suggestedFilterGroupOrder],diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.test.tsnew file mode 100644index 000000000000..84b4936040af--- /dev/null+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.test.ts@@ -0,0 +1,200 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AppContext } from '~/types'++import { taxonomicFilterLogic } from './taxonomicFilterLogic'+import { resetSearchIntentAvailabilityForTests, taxonomicSearchIntentLogic } from './taxonomicSearchIntentLogic'+import { TaxonomicFilterGroupType, TaxonomicFilterLogicProps } from './types'++window.POSTHOG_APP_CONTEXT = {+ current_team: { id: MOCK_TEAM_ID },+ current_project: { id: MOCK_TEAM_ID },+} as unknown as AppContext++const PROPS: TaxonomicFilterLogicProps = {+ taxonomicFilterLogicKey: 'search-intent-test',+ taxonomicGroupTypes: [+ TaxonomicFilterGroupType.SuggestedFilters,+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.PersonProperties,+ ],+}++const PERSON_PROPERTIES_ANSWER = {+ group_type: 'person_properties',+ confidence: 0.9,+ is_confident: true,+ suggests_switch: true,+ method: 'model',+ prompt_version: 4,+}++describe('taxonomicSearchIntentLogic', () => {+ let filterLogic: ReturnType<typeof taxonomicFilterLogic.build>+ let logic: ReturnType<typeof taxonomicSearchIntentLogic.build>+ let classifyRequests: Record<string, any>[]+ let answer: Record<string, any>++ beforeEach(() => {+ classifyRequests = []+ answer = PERSON_PROPERTIES_ANSWER+ resetSearchIntentAvailabilityForTests()+ useMocks({+ get: {+ '/api/projects/:team/property_definitions': () => [200, { results: [], count: 0 }],+ '/api/environments/:team/sessions/property_definitions': () => [200, { results: [], count: 0 }],+ '/api/projects/:team/event_definitions': () => [200, { results: [], count: 0 }],+ },+ post: {+ '/api/projects/:team/taxonomic_search_intent/classify/': async ({ request }) => {+ classifyRequests.push((await request.json()) as Record<string, any>)+ return [200, answer]+ },+ },+ })+ initKeaTests()+ filterLogic = taxonomicFilterLogic(PROPS)+ filterLogic.mount()+ logic = taxonomicSearchIntentLogic(PROPS)+ logic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ const search = async (query: string): Promise<void> => {+ filterLogic.actions.setSearchQuery(query)+ await expectLogic(logic).toFinishAllListeners()+ }++ const enroll = (variant: string | false): void => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT], {+ [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: variant,+ })+ }++ it('does not ask the model for a person outside the experiment', async () => {+ enroll(false)+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)++ await search('email')++ expect(classifyRequests).toHaveLength(0)+ expect(logic.values.intent).toBeNull()+ })++ it('suggests the tab in the banner arm and switches to it on accept', async () => {+ enroll('banner')+ const captureSpy = jest.spyOn(posthog, 'capture')+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)++ await search('email')++ expect(classifyRequests).toEqual([+ expect.objectContaining({ query: 'email', active_group_type: 'event_properties' }),+ ])+ expect(logic.values.suggestedSwitch).toEqual({+ groupType: TaxonomicFilterGroupType.PersonProperties,+ groupName: 'Person properties',+ })++ logic.actions.acceptSuggestedSwitch()++ expect(filterLogic.values.activeTab).toEqual(TaxonomicFilterGroupType.PersonProperties)+ expect(logic.values.suggestedSwitch).toBeNull()+ expect(captureSpy).toHaveBeenCalledWith('taxonomic filter search intent switched', {+ surface: 'legacy-pill',+ fromGroupType: 'event_properties',+ toGroupType: 'person_properties',+ })+ })++ it('keeps the suggestion while the next search is in flight and drops it when the answer changes', async () => {+ enroll('banner')+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)+ await search('email')++ answer = { ...PERSON_PROPERTIES_ANSWER, suggests_switch: false }+ filterLogic.actions.setSearchQuery('emails sent')+ expect(logic.values.suggestedSwitch).not.toBeNull()++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.suggestedSwitch).toBeNull()+ })++ it('drops the suggestion when the search is cleared', async () => {+ enroll('banner')+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)+ await search('email')++ await search('')++ expect(logic.values.suggestedSwitch).toBeNull()+ })++ it('records the answer in the control arm without changing the picker', async () => {+ enroll('control')+ const captureSpy = jest.spyOn(posthog, 'capture')+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)++ await search('email')++ expect(logic.values.suggestedSwitch).toBeNull()+ expect(filterLogic.values.suggestedFilterGroupOrder[0]).toEqual(TaxonomicFilterGroupType.EventProperties)+ expect(captureSpy).toHaveBeenCalledWith(+ 'taxonomic filter search intent predicted',+ expect.objectContaining({+ variant: 'control',+ predictedGroupType: 'person_properties',+ promptVersion: 4,+ suggestsSwitch: true,+ wouldPromote: false,+ shown: false,+ })+ )+ })++ it.each([+ ['on the All tab before the results reveal', TaxonomicFilterGroupType.PersonProperties, false, false],+ ['on the All tab after the results reveal', TaxonomicFilterGroupType.EventProperties, true, false],+ ['on a specific tab', TaxonomicFilterGroupType.EventProperties, false, true],+ ])('in the promote arm, an answer that lands %s puts %s first', async (_, first, revealed, onSpecificTab) => {+ enroll('promote')+ if (onSpecificTab) {+ filterLogic.actions.setActiveTab(TaxonomicFilterGroupType.EventProperties)+ }+ filterLogic.actions.setSearchQuery('email')+ if (revealed) {+ filterLogic.actions.openRevealBarrier()+ }+ await expectLogic(logic).toFinishAllListeners()++ expect(filterLogic.values.suggestedFilterGroupOrder[0]).toEqual(first)+ })++ it('stops asking after the project turns out not to be enrolled', async () => {+ enroll('banner')+ useMocks({+ post: {+ '/api/projects/:team/taxonomic_search_intent/classify/': async ({ request }) => {+ classifyRequests.push((await request.json()) as Record<string, any>)+ return [404, { detail: 'Not found.' }]+ },+ },+ })++ await search('email')+ await search('url')++ expect(classifyRequests).toHaveLength(1)+ })+})diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.tsnew file mode 100644index 000000000000..d5cb0227b717--- /dev/null+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts@@ -0,0 +1,263 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { projectLogic } from 'scenes/projectLogic'+import { sceneLogic } from 'scenes/sceneLogic'++import { taxonomicSearchIntentClassifyCreate } from '~/generated/core/api'+import type { SearchIntentResponseApi } from '~/generated/core/api.schemas'++import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'+import { taxonomicFilterLogic } from './taxonomicFilterLogic'+import { legacyTaxonomicSurface } from './taxonomicFilterSurface'+import { TaxonomicFilterGroup, TaxonomicFilterGroupType, TaxonomicFilterLogicProps } from './types'++export type SearchIntentVariant = 'control' | 'banner' | 'promote'++const SEARCH_INTENT_VARIANTS: SearchIntentVariant[] = ['control', 'banner', 'promote']++// Mirrors MIN_QUERY_CHARS and MAX_QUERY_CHARS in posthog/taxonomic_search_intent/classify.py.+const MIN_QUERY_LENGTH = 2+const MAX_QUERY_LENGTH = 64+// Longer than a keystroke gap, so a person who types a word asks once and not once per letter.+const SEARCH_INTENT_DEBOUNCE_MS = 350++export interface SearchIntent extends SearchIntentResponseApi {+ query: string+ activeTab: TaxonomicFilterGroupType+}++export interface SuggestedSwitch {+ groupType: TaxonomicFilterGroupType+ groupName: string+}++// A 404 means the project is not enrolled in decisions, so the rest of the page load does not ask again for it.+const unavailableProjectIds = new Set<number>()++export function resetSearchIntentAvailabilityForTests(): void {+ unavailableProjectIds.clear()+}++export function isSearchIntentVariant(value: unknown): value is SearchIntentVariant {+ return SEARCH_INTENT_VARIANTS.includes(value as SearchIntentVariant)+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taxonomicSearchIntentLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentProjectId: number | null // projectLogic+ activeTab: TaxonomicFilterGroupType // taxonomicFilterLogic+ revealBarrierOpen: boolean // taxonomicFilterLogic+ taxonomicGroupTypes: TaxonomicFilterGroupType[] // taxonomicFilterLogic+ taxonomicGroups: TaxonomicFilterGroup[] // taxonomicFilterLogic+ intent: SearchIntent | null+ suggestedSwitch: SuggestedSwitch | null+ variant: SearchIntentVariant | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taxonomicSearchIntentLogicActions {+ setActiveTab: (activeTab: TaxonomicFilterGroupType) => {+ activeTab: TaxonomicFilterGroupType+ } // taxonomicFilterLogic+ setIntentPromotedGroupType: (groupType: TaxonomicFilterGroupType | null) => {+ groupType: TaxonomicFilterGroupType | null+ } // taxonomicFilterLogic+ setSearchQuery: (searchQuery: string) => {+ searchQuery: string+ } // taxonomicFilterLogic+ acceptSuggestedSwitch: () => {+ value: true+ }+ setIntent: (intent: SearchIntent | null) => {+ intent: SearchIntent | null+ }+ setVariant: (variant: SearchIntentVariant) => {+ variant: SearchIntentVariant+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taxonomicSearchIntentLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ suggestedSwitch: (+ intent: SearchIntent | null,+ variant: SearchIntentVariant | null,+ activeTab: TaxonomicFilterGroupType,+ taxonomicGroupTypes: TaxonomicFilterGroupType[],+ taxonomicGroups: TaxonomicFilterGroup[]+ ) => SuggestedSwitch | null+ }+}++export type taxonomicSearchIntentLogicType = MakeLogicType<+ taxonomicSearchIntentLogicValues,+ taxonomicSearchIntentLogicActions,+ TaxonomicFilterLogicProps,+ taxonomicSearchIntentLogicMeta+>++/**+ * Asks the decision model which tab a picker search belongs to, for the `taxonomic-filter-search-intent`+ * experiment. Every arm asks, so control records what the other arms would have shown. Legacy surface only.+ */+export const taxonomicSearchIntentLogic = kea<taxonomicSearchIntentLogicType>([+ props({} as TaxonomicFilterLogicProps),+ key((props) => `${props.taxonomicFilterLogicKey}`),+ path((key) => ['lib', 'components', 'TaxonomicFilter', 'taxonomicSearchIntentLogic', key]),+ connect((props: TaxonomicFilterLogicProps) => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ projectLogic,+ ['currentProjectId'],+ taxonomicFilterLogic(props),+ ['activeTab', 'revealBarrierOpen', 'taxonomicGroupTypes', 'taxonomicGroups'],+ ],+ actions: [taxonomicFilterLogic(props), ['setActiveTab', 'setIntentPromotedGroupType', 'setSearchQuery']],+ })),+ actions({+ setIntent: (intent: SearchIntent | null) => ({ intent }),+ setVariant: (variant: SearchIntentVariant) => ({ variant }),+ acceptSuggestedSwitch: true,+ }),+ reducers({+ intent: [+ null as SearchIntent | null,+ {+ // A new search keeps the last answer until its own answer arrives, so the banner does not flash per keystroke.+ setIntent: (_, { intent }) => intent,+ },+ ],+ variant: [+ null as SearchIntentVariant | null,+ {+ setVariant: (_, { variant }) => variant,+ },+ ],+ }),+ selectors({+ suggestedSwitch: [+ (s) => [s.intent, s.variant, s.activeTab, s.taxonomicGroupTypes, s.taxonomicGroups],+ (+ intent: SearchIntent | null,+ variant: SearchIntentVariant | null,+ activeTab: TaxonomicFilterGroupType,+ taxonomicGroupTypes: TaxonomicFilterGroupType[],+ taxonomicGroups: TaxonomicFilterGroup[]+ ): SuggestedSwitch | null => {+ if (+ variant !== 'banner' ||+ !intent?.suggests_switch ||+ !intent.group_type ||+ intent.activeTab !== activeTab+ ) {+ return null+ }+ const groupType = intent.group_type as TaxonomicFilterGroupType+ if (!taxonomicGroupTypes.includes(groupType)) {+ return null+ }+ const groupName = taxonomicGroups.find((group) => group.type === groupType)?.name ?? groupType+ return { groupType, groupName }+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ setSearchQuery: async ({ searchQuery }, breakpoint) => {+ const query = searchQuery.trim()+ if (query.length < MIN_QUERY_LENGTH || query.length > MAX_QUERY_LENGTH) {+ actions.setIntent(null)+ return+ }+ if (values.currentProjectId !== null && unavailableProjectIds.has(values.currentProjectId)) {+ return+ }+ await breakpoint(SEARCH_INTENT_DEBOUNCE_MS)++ // Read the flag only for a search the model can answer, so exposure means "could have seen a change".+ const variant = values.variant ?? values.featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]+ const projectId = values.currentProjectId+ if (!isSearchIntentVariant(variant) || projectId === null) {+ return+ }+ if (values.variant === null) {+ actions.setVariant(variant)+ }++ const activeTab = values.activeTab+ let response: SearchIntentResponseApi+ try {+ response = await taxonomicSearchIntentClassifyCreate(String(projectId), {+ query,+ active_group_type: activeTab,+ available_group_types: values.taxonomicGroupTypes,+ scene: sceneLogic.findMounted()?.values.activeSceneId ?? null,+ })+ } catch (error: any) {+ if (error?.status === 404) {+ unavailableProjectIds.add(projectId)+ }+ breakpoint()+ actions.setIntent(null)+ return+ }+ breakpoint()+ actions.setIntent({ ...response, query, activeTab })+ },+ setIntent: ({ intent }) => {+ if (!intent || !values.variant) {+ return+ }+ // Only the All tab reads the promoted group order, so a promotion from another tab changes nothing.+ const canPromote =+ intent.method === 'model' &&+ intent.is_confident &&+ !!intent.group_type &&+ intent.activeTab === TaxonomicFilterGroupType.SuggestedFilters+ // Promote only while the results still show skeletons, so no row moves under the cursor.+ const promoted =+ values.variant === 'promote' &&+ canPromote &&+ !values.revealBarrierOpen &&+ values.activeTab === intent.activeTab+ if (promoted) {+ actions.setIntentPromotedGroupType(intent.group_type as TaxonomicFilterGroupType)+ }+ // pinned: analytics event name and properties, the experiment reads them+ posthog.capture('taxonomic filter search intent predicted', {+ surface: legacyTaxonomicSurface(),+ variant: values.variant,+ activeTab: intent.activeTab,+ predictedGroupType: intent.group_type,+ confidence: intent.confidence,+ isConfident: intent.is_confident,+ source: intent.method,+ promptVersion: intent.prompt_version,+ suggestsSwitch: intent.suggests_switch,+ wouldPromote: canPromote,+ shown: values.variant === 'banner' ? !!values.suggestedSwitch : promoted,+ // Only a model answer carries the query. The server keeps emails, URLs, paths, digit runs and opaque tokens+ // from the model, so those never appear here, but other free text such as a name still does.+ query: intent.method === 'model' ? intent.query : undefined,+ })+ },+ acceptSuggestedSwitch: () => {+ const suggestion = values.suggestedSwitch+ if (!suggestion) {+ return+ }+ // pinned: analytics event name, the experiment reads it+ posthog.capture('taxonomic filter search intent switched', {+ surface: legacyTaxonomicSurface(),+ fromGroupType: values.activeTab,+ toGroupType: suggestion.groupType,+ })+ actions.setActiveTab(suggestion.groupType)+ },+ })),+])diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 62a6b97fb746..062ca75326e9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -526,6 +526,7 @@ export const FEATURE_FLAGS = {TASKS: 'tasks', // owner: #team-ai-observabilityTASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observabilityTAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)+ TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model, then suggests the right tab (banner) or promotes its group (promote)TEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cardsTOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pyindex c106ff3cbfd2..8cfd0eb4d430 100644--- a/posthog/api/rest_router.py+++ b/posthog/api/rest_router.py@@ -85,6 +85,7 @@ from .llm_prompt import LLMPromptViewSetfrom .oauth import OrganizationOAuthApplicationViewSetfrom .organization_notification_locks import OrganizationNotificationLockViewSetfrom .session import SessionViewSet+from .taxonomic_search_intent import SearchIntentViewSet@decorators.api_view(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])@@ -241,6 +242,12 @@ projects_router.register("project_property_definitions",["project_id"],)+projects_router.register(+ r"taxonomic_search_intent",+ SearchIntentViewSet,+ "project_taxonomic_search_intent",+ ["team_id"],+)projects_router.register(r"schema_property_groups",schema_property_group.SchemaPropertyGroupViewSet,diff --git a/posthog/api/taxonomic_search_intent.py b/posthog/api/taxonomic_search_intent.pynew file mode 100644index 000000000000..8db1d41e939e--- /dev/null+++ b/posthog/api/taxonomic_search_intent.py@@ -0,0 +1,147 @@+"""+The filter picker's search intent endpoint: which tab does a search belong to?++Validate JSON via serializers, call the classifier, return serialized responses. No business logic here.+"""++from typing import Any, cast++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import APIException, NotFound+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import UserRateThrottle++from posthog.api.mixins import validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.llm.system_one import SystemOneNotConfigured, SystemOneRequestFailed+from posthog.models import User+from posthog.taxonomic_search_intent.classify import classify_search_intent, search_intent_enabled+from posthog.taxonomic_search_intent.contracts import SearchIntentRequest, SearchIntentSource++logger = structlog.get_logger(__name__)++MAX_SEARCH_QUERY_CHARS = 200+MAX_GROUP_TYPE_CHARS = 100+MAX_GROUP_TYPES = 64+++class SearchIntentRequestSerializer(serializers.Serializer):+ query = serializers.CharField(+ max_length=MAX_SEARCH_QUERY_CHARS,+ allow_blank=True,+ trim_whitespace=True,+ help_text="What the person typed into the filter picker search box.",+ )+ active_group_type = serializers.CharField(+ max_length=MAX_GROUP_TYPE_CHARS,+ help_text="The picker tab that is open, as a taxonomic group type such as event_properties.",+ )+ available_group_types = serializers.ListField(+ child=serializers.CharField(max_length=MAX_GROUP_TYPE_CHARS),+ max_length=MAX_GROUP_TYPES,+ help_text="The taxonomic group types the picker shows. The answer is always one of these, or null.",+ )+ scene = serializers.RegexField(+ r"^[A-Za-z0-9_-]{1,64}$",+ required=False,+ allow_null=True,+ help_text="The id of the scene the picker is open in, such as Insight or Replay.",+ )+++class SearchIntentResponseSerializer(serializers.Serializer):+ group_type = serializers.CharField(+ allow_null=True,+ help_text="The taxonomic group type the search most likely belongs to, or null if it was not classified.",+ )+ confidence = serializers.FloatField(+ help_text="How far the chosen group stands out from the rest, from 0 (a coin flip) to 1.",+ )+ is_confident = serializers.BooleanField(+ help_text="Whether the confidence is high enough to act on, for example to suggest a different tab.",+ )+ suggests_switch = serializers.BooleanField(+ help_text="Whether the picker should suggest switching from the open tab to group_type.",+ )+ method = serializers.ChoiceField(+ choices=SearchIntentSource.choices,+ help_text="How the answer was found: a value pattern, the decision model, or not at all.",+ )+ prompt_version = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "The version of the managed search intent prompt the model read. Null for a value pattern, "+ "a skipped search, or the bundled fallback prompt."+ ),+ )+++class SearchIntentUnavailable(APIException):+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_detail = "The decision model is not available right now. Try again in a moment."+ default_code = "search_intent_unavailable"+++# One search box sends one request per pause in typing, so these rates are far above the AI throttles and+# are separate from them: a person who filters a lot must not lose their PostHog AI budget.+class SearchIntentBurstThrottle(UserRateThrottle):+ scope = "taxonomic_search_intent_burst"+ rate = "120/minute"+++class SearchIntentSustainedThrottle(UserRateThrottle):+ scope = "taxonomic_search_intent_sustained"+ rate = "3000/day"+++@extend_schema(extensions={"x-product": "core"})+class SearchIntentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "INTERNAL"+ serializer_class = SearchIntentRequestSerializer+ throttle_classes = [SearchIntentBurstThrottle, SearchIntentSustainedThrottle]++ @validated_request(+ request_serializer=SearchIntentRequestSerializer,+ responses={+ 200: OpenApiResponse(response=SearchIntentResponseSerializer, description="The most likely tab."),+ 404: OpenApiResponse(description="Search intent is not enabled for this person."),+ 503: OpenApiResponse(description="The decision model did not answer in time."),+ },+ summary="Classify a filter picker search",+ description="Guess which filter picker tab a search belongs to, so the picker can suggest or promote it.",+ )+ @action(detail=False, methods=["POST"])+ def classify(self, request: Request, **kwargs: Any) -> Response:+ data = request.validated_data+ search = SearchIntentRequest(+ team_id=self.team_id,+ query=data["query"],+ active_group_type=data["active_group_type"],+ available_group_types=tuple(data["available_group_types"]),+ scene=data.get("scene"),+ )+ user = cast(User, request.user)+ if not search_intent_enabled(str(user.distinct_id), str(self.organization_id)):+ raise NotFound()+ try:+ intent = classify_search_intent(search)+ except (SystemOneNotConfigured, SystemOneRequestFailed) as error:+ # The picker works without an answer, so every model failure is the same "not now" to the caller.+ logger.warning("taxonomic_search_intent_unavailable", team_id=self.team_id, reason=type(error).__name__)+ raise SearchIntentUnavailable() from error+ return Response(+ SearchIntentResponseSerializer(+ {+ "group_type": intent.group_type,+ "confidence": intent.confidence,+ "is_confident": intent.is_confident,+ "suggests_switch": intent.suggests_switch,+ "method": intent.source,+ "prompt_version": intent.prompt_version,+ }+ ).data+ )diff --git a/posthog/api/test/test_taxonomic_search_intent.py b/posthog/api/test/test_taxonomic_search_intent.pynew file mode 100644index 000000000000..50a4f81c0784--- /dev/null+++ b/posthog/api/test/test_taxonomic_search_intent.py@@ -0,0 +1,100 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cache+from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++from posthog.llm.gateway_client import team_distinct_id+from posthog.llm.system_one import ChoiceAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult+from posthog.taxonomic_search_intent.prompt import BUNDLED_SEARCH_INTENT_PROMPT++ALL_TABS = ("suggested_filters", "events", "event_properties", "person_properties", "pageview_urls", "email_addresses")+BUILD_CLIENT = "posthog.taxonomic_search_intent.classify.build_system_one_client"+CURRENT_PROMPT = "posthog.taxonomic_search_intent.classify.current_search_intent_prompt"+FLAG_CHECK = "posthog.taxonomic_search_intent.classify.posthoganalytics.feature_enabled"+++def _answer(choice: str, confidence: float) -> SystemOneResult:+ return SystemOneResult(+ model="jevk5-0.2",+ answers={"tab": ChoiceAnswer(choice=choice, confidence=confidence, probabilities={choice: confidence})},+ input_tokens=90,+ )+++@override_settings(CLOUD_DEPLOYMENT="US")+class TestSearchIntentEndpoint(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()+ patch(CURRENT_PROMPT, return_value=BUNDLED_SEARCH_INTENT_PROMPT).start()+ self.addCleanup(patch.stopall)++ def _post(self, body: dict | None = None):+ return self.client.post(+ f"/api/projects/{self.team.id}/taxonomic_search_intent/classify/",+ body or {"query": "email", "active_group_type": "events", "available_group_types": list(ALL_TABS)},+ format="json",+ )++ @patch(BUILD_CLIENT)+ @patch(FLAG_CHECK, return_value=True)+ def test_returns_the_tab_for_the_team(self, enabled, build) -> None:+ build.return_value.decide.return_value = _answer("person_properties", 0.9)++ response = self._post()++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json() == {+ "group_type": "person_properties",+ "confidence": 0.9,+ "is_confident": True,+ "suggests_switch": True,+ "method": "model",+ "prompt_version": None,+ }+ assert build.call_args.kwargs["distinct_id"] == team_distinct_id(self.team.id)+ assert enabled.call_args.args == ("taxonomic-filter-search-intent", str(self.user.distinct_id))++ @parameterized.expand(+ [+ ("disabled", "US", False, None, status.HTTP_404_NOT_FOUND),+ ("eu_cloud", "EU", True, None, status.HTTP_404_NOT_FOUND),+ ("self_hosted", None, True, None, status.HTTP_404_NOT_FOUND),+ ("not_configured", "US", True, SystemOneNotConfigured("no gateway"), status.HTTP_503_SERVICE_UNAVAILABLE),+ ("unreachable", "US", True, SystemOneRequestFailed("timeout"), status.HTTP_503_SERVICE_UNAVAILABLE),+ (+ "refused",+ "US",+ True,+ SystemOneRequestFailed("boom", status_code=500),+ status.HTTP_503_SERVICE_UNAVAILABLE,+ ),+ ]+ )+ def test_the_picker_gets_a_plain_failure_when_there_is_no_answer(+ self, _name, region, enabled, error, expected_status+ ) -> None:+ with (+ self.settings(CLOUD_DEPLOYMENT=region),+ patch(FLAG_CHECK, return_value=enabled),+ patch(BUILD_CLIENT, side_effect=error),+ ):+ response = self._post()++ assert response.status_code == expected_status++ def test_rejects_a_scene_that_is_not_an_id(self) -> None:+ response = self._post(+ {+ "query": "email",+ "active_group_type": "events",+ "available_group_types": ["events"],+ "scene": "https://example.com/[email protected]",+ }+ )++ assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/posthog/taxonomic_search_intent/__init__.py b/posthog/taxonomic_search_intent/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/taxonomic_search_intent/classify.py b/posthog/taxonomic_search_intent/classify.pynew file mode 100644index 000000000000..b4700de01737--- /dev/null+++ b/posthog/taxonomic_search_intent/classify.py@@ -0,0 +1,204 @@+"""+Classify a filter picker search: which tab (taxonomic group) does the person look for?++Value-shaped input (an email address, a URL, a path) is matched by pattern and never goes to the model.+Everything else is one multiple choice question to the decision model, over the tabs the picker shows.+"""++import re+import hashlib+import dataclasses++from django.conf import settings+from django.core.cache import cache++import structlog+import posthoganalytics+from pydantic import TypeAdapter, ValidationError++from posthog.llm.gateway_client import team_distinct_id+from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion+from posthog.llm.system_one_client import build_system_one_client++from .contracts import SearchIntent, SearchIntentRequest, SearchIntentSource+from .prompt import SearchIntentPrompt, current_search_intent_prompt++logger = structlog.get_logger(__name__)++SEARCH_INTENT_FEATURE_FLAG = "taxonomic-filter-search-intent"+SEARCH_INTENT_MODEL = "posthog/hogference/jevk5-fp8-0.2"+MIN_QUERY_CHARS = 2+MAX_QUERY_CHARS = 64+# The picker waits for no answer, so a late answer is worth nothing and a short timeout frees the worker.+SEARCH_INTENT_TIMEOUT_SECONDS = 2.0+CACHE_TTL_SECONDS = 24 * 60 * 60+# Keyed per team: a cache shared across teams lets a fast answer tell one team what another team searched.+CACHE_KEY_PREFIX = "taxonomic_search_intent:v1"++_EMAIL_VALUE = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", re.IGNORECASE)+_URL_VALUE = re.compile(r"^(https?://|www\.)", re.IGNORECASE)+# Any leading slash, because a query string or a fragment can carry a token or personal data.+_PATH_VALUE = re.compile(r"^/")+# Long digit runs are ids or phone numbers, which are not ours to send.+_DIGIT_RUN = re.compile(r"\d{6,}")+# One word of 8+ characters that mixes letters with two or more digits is a token or an id, such as a session id.+_OPAQUE_TOKEN = re.compile(r"^(?=\S*[a-z])(?=\S*\d\S*\d)\S{8,}$", re.IGNORECASE)+_SCENE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")++_QUESTION_ID = "tab"+# The Django cache pickles what it stores, so the intent goes in as JSON text and comes out schema-validated.+_CACHED_INTENT = TypeAdapter(SearchIntent)+++def search_intent_enabled(distinct_id: str, organization_id: str) -> bool:+ """The flag assigns the experiment arms. Every arm asks, so any value other than off enables the endpoint.++ Dark launch: only local development and the US cloud, so no flag change can bring it up in the EU or on+ self-hosted. DEBUG bypasses the flag because the analytics SDK is disabled in local development.+ """+ if not (settings.DEBUG or (settings.CLOUD_DEPLOYMENT or "").upper() == "US"):+ return False+ if settings.DEBUG:+ return True+ try:+ return bool(+ posthoganalytics.feature_enabled(+ SEARCH_INTENT_FEATURE_FLAG,+ distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("taxonomic_search_intent_flag_check_failed")+ return False+++def _skipped() -> SearchIntent:+ return SearchIntent(group_type=None, confidence=0.0, is_confident=False, source=SearchIntentSource.SKIPPED)+++def _rule_match(group_type: str) -> SearchIntent:+ return SearchIntent(group_type=group_type, confidence=1.0, is_confident=True, source=SearchIntentSource.RULE)+++def rule_intent(query: str, available_group_types: tuple[str, ...]) -> SearchIntent | None:+ """Match value-shaped input. None means the query is not a value and the model can read it."""+ if "@" in query:+ if _EMAIL_VALUE.match(query) and "email_addresses" in available_group_types:+ return _rule_match("email_addresses")+ if _EMAIL_VALUE.match(query) and "person_properties" in available_group_types:+ return _rule_match("person_properties")+ # A partial email address is still personal data, so it never goes to the model.+ return _skipped()+ if _URL_VALUE.match(query) or _PATH_VALUE.match(query):+ if "pageview_urls" in available_group_types:+ return _rule_match("pageview_urls")+ return _skipped()+ if _DIGIT_RUN.search(query) or any(_OPAQUE_TOKEN.match(word) for word in query.split()):+ return _skipped()+ return None+++def search_intent_state(query: str, active_group_type: str, scene: str | None) -> str:+ lines = ["A person uses the filter picker in PostHog, a product analytics tool."]+ if scene and _SCENE.match(scene):+ lines.append(f"Page: {scene}")+ lines.append(f"Open tab: {active_group_type}")+ lines.append(f"Search: {query}")+ return "\n".join(lines)+++def _cache_key(+ team_id: int, model: str, state: str, instructions: str, options: dict[str, str], threshold: float+) -> str:+ # The prompt text is in the key, not its version, so a new managed version and the bundled copy never share answers.+ parts = [model, state, instructions, str(threshold), *(f"{k}={v}" for k, v in sorted(options.items()))]+ digest = hashlib.sha256("\n".join(parts).encode()).hexdigest()+ return f"{CACHE_KEY_PREFIX}:{team_id}:{digest}"+++# The cross-category tab already shows every group, so there is no better tab to suggest from it.+_ALL_GROUPS_TAB = "suggested_filters"+++def with_switch_suggestion(intent: SearchIntent, active_group_type: str) -> SearchIntent:+ """Suggest a different tab only for a confident answer that names a tab other than the open one."""+ suggests_switch = (+ intent.is_confident+ and intent.group_type is not None+ and intent.group_type != active_group_type+ and active_group_type != _ALL_GROUPS_TAB+ )+ return dataclasses.replace(intent, suggests_switch=suggests_switch)+++def classify_search_intent(+ request: SearchIntentRequest, *, use_cache: bool = True, prompt: SearchIntentPrompt | None = None+) -> SearchIntent:+ """Raises the System One errors; the caller decides whether a failed answer matters."""+ prompt = prompt or current_search_intent_prompt()+ return with_switch_suggestion(_classify(request, prompt, use_cache=use_cache), request.active_group_type)+++def _classify(request: SearchIntentRequest, prompt: SearchIntentPrompt, *, use_cache: bool) -> SearchIntent:+ query = " ".join(request.query.split())+ if not MIN_QUERY_CHARS <= len(query) <= MAX_QUERY_CHARS:+ return _skipped()+ matched = rule_intent(query, request.available_group_types)+ if matched is not None:+ return matched++ options = {+ group_type: meaning+ for group_type, meaning in prompt.options.items()+ if group_type in request.available_group_types+ }+ if len(options) < 2:+ return _skipped()++ state = search_intent_state(query, request.active_group_type, request.scene)+ key = _cache_key(+ request.team_id, SEARCH_INTENT_MODEL, state, prompt.instructions, options, prompt.confident_threshold+ )+ if use_cache:+ cached = _cached_intent(key)+ if cached is not None:+ return cached++ # No TypeSafe fallback: a search is customer text, and TypeSafe is a third party.+ client = build_system_one_client(+ model=SEARCH_INTENT_MODEL,+ ai_product="taxonomic_filter",+ distinct_id=team_distinct_id(request.team_id),+ timeout=SEARCH_INTENT_TIMEOUT_SECONDS,+ )+ result = client.decide(+ state=state, questions={_QUESTION_ID: ChoiceQuestion(instructions=prompt.instructions, criteria=options)}+ )+ answer = result.answers[_QUESTION_ID]+ if not isinstance(answer, ChoiceAnswer) or answer.choice not in options:+ logger.warning("taxonomic_search_intent_unexpected_answer", team_id=request.team_id)+ return _skipped()+ intent = SearchIntent(+ group_type=answer.choice,+ confidence=answer.confidence,+ is_confident=answer.confidence >= prompt.confident_threshold,+ source=SearchIntentSource.MODEL,+ prompt_version=prompt.version,+ )+ if use_cache:+ cache.set(key, _CACHED_INTENT.dump_json(intent).decode(), CACHE_TTL_SECONDS)+ return intent+++def _cached_intent(key: str) -> SearchIntent | None:+ cached = cache.get(key)+ if not isinstance(cached, str):+ return None+ try:+ return _CACHED_INTENT.validate_json(cached)+ except ValidationError:+ return Nonediff --git a/posthog/taxonomic_search_intent/contracts.py b/posthog/taxonomic_search_intent/contracts.pynew file mode 100644index 000000000000..0929e4775140--- /dev/null+++ b/posthog/taxonomic_search_intent/contracts.py@@ -0,0 +1,33 @@+from django.db import models++from posthog.dataclasses import frozen+++class SearchIntentSource(models.TextChoices):+ RULE = "rule", "Matched a value pattern"+ MODEL = "model", "Asked the decision model"+ SKIPPED = "skipped", "Not classified"+++@frozen+class SearchIntentRequest:+ """What a person typed into the filter picker, and the tabs the picker shows them."""++ team_id: int+ query: str+ active_group_type: str+ available_group_types: tuple[str, ...]+ scene: str | None = None+++@frozen+class SearchIntent:+ """The picker tab the search most likely belongs to. ``group_type`` is None when nothing was classified."""++ group_type: str | None+ confidence: float+ is_confident: bool+ source: SearchIntentSource+ suggests_switch: bool = False+ # The managed prompt version the model read, or None for a rule match, a skip or the bundled prompt.+ prompt_version: int | None = Nonediff --git a/posthog/taxonomic_search_intent/prompt.py b/posthog/taxonomic_search_intent/prompt.pynew file mode 100644index 000000000000..7bd40820b538--- /dev/null+++ b/posthog/taxonomic_search_intent/prompt.py@@ -0,0 +1,158 @@+"""+The question and the tab meanings the decision model reads for a filter picker search.++They live in PostHog's own prompt management, as `taxonomic-filter-search-intent` in the PostHog project,+so a new wording ships by moving the `production` label and not by a deploy. The prompt text is the+question. Its config holds the tab meanings as `options` and the `confident_threshold`. The bundled+copy below is the fallback when the managed prompt is unreachable or malformed; keep it close to the+`production` version so a fallback answer reads the same.+"""++import time+import threading+from collections.abc import Mapping+from concurrent.futures import ThreadPoolExecutor+from typing import Any++import structlog+import posthoganalytics+from posthoganalytics.ai.prompts import PromptResult, Prompts++from posthog.dataclasses import frozen+from posthog.llm.system_one_client import GATEWAY_MAX_CHOICE_OPTIONS++logger = structlog.get_logger(__name__)++SEARCH_INTENT_PROMPT_NAME = "taxonomic-filter-search-intent"+SEARCH_INTENT_PROMPT_LABEL = "production"+PROMPT_REFRESH_SECONDS = 60+++@frozen+class SearchIntentPrompt:+ instructions: str+ options: Mapping[str, str]+ confident_threshold: float+ # None for the bundled copy, so analysis can tell a fallback answer from a managed one.+ version: int | None+++BUNDLED_SEARCH_INTENT_PROMPT = SearchIntentPrompt(+ instructions="Which tab of the filter picker holds the thing this person searches for?",+ options={+ "events": "An event: something a person did, such as a pageview, a signup, a purchase or a click.",+ "actions": "A saved action: a named combination of events.",+ "event_properties": (+ "A property of one event, such as the current URL, path, browser, device, UTM tags, referrer "+ "or the country the event came from."+ ),+ "person_properties": (+ "A property of a person, such as their email address, name, company, plan or the date they signed up."+ ),+ "session_properties": (+ "A property of a whole session, such as its duration, entry URL, exit URL or channel type."+ ),+ "cohorts": "A saved cohort: a named group of people.",+ "feature_flags": "A feature flag, or the people who match a feature flag.",+ "event_feature_flags": "The value of a feature flag that was active when an event happened.",+ "pageview_urls": "One specific page URL.",+ "email_addresses": "One specific person's email address.",+ "elements": "An element on the page, such as a button, a link or a form field.",+ },+ # The frontend acts on an answer only above this confidence. Tune it from the eval suite, not by feel.+ confident_threshold=0.6,+ version=None,+)+++def _valid_options(value: Any) -> dict[str, str] | None:+ # The gateway refuses a choice question with more options than this before it sends anything.+ if not isinstance(value, dict) or not 1 <= len(value) <= GATEWAY_MAX_CHOICE_OPTIONS:+ return None+ if not all(isinstance(k, str) and isinstance(v, str) and v.strip() for k, v in value.items()):+ return None+ return {k: v.strip() for k, v in value.items()}+++def _valid_threshold(value: Any) -> float | None:+ if isinstance(value, bool) or not isinstance(value, int | float) or not 0 < value <= 1:+ return None+ return float(value)+++def parse_search_intent_prompt(result: PromptResult) -> SearchIntentPrompt:+ """A malformed part falls back to the bundled part, so one bad config key never stops the picker."""+ if result.source == "code_fallback":+ return BUNDLED_SEARCH_INTENT_PROMPT+ config = result.config or {}+ options = _valid_options(config.get("options"))+ threshold = _valid_threshold(config.get("confident_threshold"))+ if options is None or threshold is None:+ logger.warning(+ "taxonomic_search_intent_prompt_config_invalid",+ version=result.version,+ options_valid=options is not None,+ threshold_valid=threshold is not None,+ )+ bundled = BUNDLED_SEARCH_INTENT_PROMPT+ return SearchIntentPrompt(+ instructions=result.prompt.strip() or bundled.instructions,+ options=options if options is not None else bundled.options,+ confident_threshold=threshold if threshold is not None else bundled.confident_threshold,+ version=result.version,+ )+++def fetch_search_intent_prompt(*, label: str | None = None, version: int | None = None) -> SearchIntentPrompt:+ """Blocks on the network for up to the SDK timeout. Request code reads `current_search_intent_prompt` instead."""+ # Without a key (tests, local dev, self-hosted) the SDK still sends the request and gets a 401.+ if not posthoganalytics.personal_api_key:+ return BUNDLED_SEARCH_INTENT_PROMPT+ # Built per fetch because the key is set in apps.ready(), after this module can be imported.+ prompts = Prompts(posthoganalytics, capture_errors=True)+ result = prompts.get(+ SEARCH_INTENT_PROMPT_NAME,+ with_metadata=True,+ label=label if version is None else None,+ version=version,+ fallback=BUNDLED_SEARCH_INTENT_PROMPT.instructions,+ )+ return parse_search_intent_prompt(result)+++class _PromptRefresher:+ # The SDK fetch blocks for up to 10 s on a cache miss and the picker's budget is 2 s, so a request+ # reads the last prompt it has and at most one background fetch replaces it.+ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search-intent-prompt")+ self._prompt = BUNDLED_SEARCH_INTENT_PROMPT+ self._refreshed_at = float("-inf")+ self._refreshing = False++ def current(self) -> SearchIntentPrompt:+ with self._lock:+ if not self._refreshing and time.monotonic() - self._refreshed_at >= PROMPT_REFRESH_SECONDS:+ self._refreshing = True+ self._executor.submit(self._refresh)+ return self._prompt++ def _refresh(self) -> None:+ try:+ prompt = fetch_search_intent_prompt(label=SEARCH_INTENT_PROMPT_LABEL)+ except Exception:+ logger.exception("taxonomic_search_intent_prompt_refresh_failed")+ prompt = None+ with self._lock:+ if prompt is not None and (prompt.version is not None or self._prompt.version is None):+ self._prompt = prompt+ self._refreshed_at = time.monotonic()+ self._refreshing = False+++_REFRESHER = _PromptRefresher()+++def current_search_intent_prompt() -> SearchIntentPrompt:+ """Never blocks. The first requests after boot read the bundled copy until the first fetch lands."""+ return _REFRESHER.current()diff --git a/posthog/taxonomic_search_intent/test_classify.py b/posthog/taxonomic_search_intent/test_classify.pynew file mode 100644index 000000000000..ad35f9f5d996--- /dev/null+++ b/posthog/taxonomic_search_intent/test_classify.py@@ -0,0 +1,242 @@+import threading+import dataclasses+from concurrent.futures import Future++from unittest.mock import patch++from django.core.cache import cache+from django.test import SimpleTestCase++from parameterized import parameterized+from posthoganalytics.ai.prompts import PromptResult++from posthog.llm.system_one import ChoiceAnswer, SystemOneResult+from posthog.taxonomic_search_intent.classify import classify_search_intent+from posthog.taxonomic_search_intent.contracts import SearchIntent, SearchIntentRequest, SearchIntentSource+from posthog.taxonomic_search_intent.prompt import (+ BUNDLED_SEARCH_INTENT_PROMPT,+ SearchIntentPrompt,+ _PromptRefresher,+ parse_search_intent_prompt,+)++ALL_TABS = ("suggested_filters", "events", "event_properties", "person_properties", "pageview_urls", "email_addresses")+++def _search(+ query: str, available: tuple[str, ...] = ALL_TABS, active: str = "events", team_id: int = 7+) -> SearchIntentRequest:+ return SearchIntentRequest(+ team_id=team_id, query=query, active_group_type=active, available_group_types=available, scene="Insight"+ )+++BUILD_CLIENT = "posthog.taxonomic_search_intent.classify.build_system_one_client"+CURRENT_PROMPT = "posthog.taxonomic_search_intent.classify.current_search_intent_prompt"+++def _answer(choice: str, confidence: float) -> SystemOneResult:+ return SystemOneResult(+ model="jevk5-0.2",+ answers={"tab": ChoiceAnswer(choice=choice, confidence=confidence, probabilities={choice: confidence})},+ input_tokens=90,+ )+++class TestClassifySearchIntent(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()+ build = patch(BUILD_CLIENT).start()+ patch(CURRENT_PROMPT, return_value=BUNDLED_SEARCH_INTENT_PROMPT).start()+ self.addCleanup(patch.stopall)+ self.decide = build.return_value.decide++ @parameterized.expand(+ [+ ("email_value", "[email protected]", ALL_TABS, "email_addresses", SearchIntentSource.RULE),+ (+ "email_value_without_email_tab",+ "[email protected]",+ ("events", "person_properties"),+ "person_properties",+ SearchIntentSource.RULE,+ ),+ ("partial_email", "ada@exa", ALL_TABS, None, SearchIntentSource.SKIPPED),+ ("url_value", "https://example.com/pricing", ALL_TABS, "pageview_urls", SearchIntentSource.RULE),+ ("path_value", "/pricing", ALL_TABS, "pageview_urls", SearchIntentSource.RULE),+ ("path_with_query", "/reset?token=abc", ALL_TABS, "pageview_urls", SearchIntentSource.RULE),+ (+ "path_without_url_tab",+ "/search?q=ada",+ ("events", "person_properties"),+ None,+ SearchIntentSource.SKIPPED,+ ),+ ("id_like", "user 12345678", ALL_TABS, None, SearchIntentSource.SKIPPED),+ ("opaque_token", "sess_a1b2c3d4", ALL_TABS, None, SearchIntentSource.SKIPPED),+ ("opaque_token_in_words", "session sess_a1b2c3d4", ALL_TABS, None, SearchIntentSource.SKIPPED),+ ("too_short", "e", ALL_TABS, None, SearchIntentSource.SKIPPED),+ ("one_option_left", "email", ("events", "suggested_filters"), None, SearchIntentSource.SKIPPED),+ ]+ )+ def test_never_asks_the_model_about_values_or_unanswerable_searches(+ self, _name: str, query: str, available: tuple[str, ...], expected: str | None, source+ ) -> None:+ intent = classify_search_intent(_search(query, available))++ assert (intent.group_type, intent.source) == (expected, source)+ self.decide.assert_not_called()++ def test_offers_only_the_tabs_the_picker_shows(self) -> None:+ self.decide.return_value = _answer("person_properties", 0.9)++ intent = classify_search_intent(_search("email"))++ assert intent == SearchIntent(+ group_type="person_properties",+ confidence=0.9,+ is_confident=True,+ source=SearchIntentSource.MODEL,+ suggests_switch=True,+ )+ sent = self.decide.call_args.kwargs+ assert set(sent["questions"]["tab"].criteria) == {+ "events",+ "event_properties",+ "person_properties",+ "pageview_urls",+ "email_addresses",+ }+ assert "Search: email" in sent["state"]++ @parameterized.expand(+ [+ ("confident_other_tab", "person_properties", 0.9, "events", True),+ ("weak_answer", "person_properties", 0.3, "events", False),+ ("already_on_that_tab", "person_properties", 0.9, "person_properties", False),+ ("on_the_all_tab", "person_properties", 0.9, "suggested_filters", False),+ ]+ )+ def test_suggests_a_switch_only_for_a_confident_different_tab(+ self, _name: str, choice: str, confidence: float, active: str, expected: bool+ ) -> None:+ self.decide.return_value = _answer(choice, confidence)++ assert classify_search_intent(_search("email", active=active)).suggests_switch is expected++ def test_an_answer_outside_the_offered_tabs_is_dropped(self) -> None:+ self.decide.return_value = _answer("cohorts", 0.99)++ assert classify_search_intent(_search("paying users")).source == SearchIntentSource.SKIPPED++ def test_asks_with_the_managed_prompt(self) -> None:+ self.decide.return_value = _answer("person_properties", 0.9)+ prompt = SearchIntentPrompt(+ instructions="Which tab?",+ options={"events": "An event.", "person_properties": "A person property."},+ confident_threshold=0.95,+ version=7,+ )++ intent = classify_search_intent(_search("email"), prompt=prompt)++ assert (intent.is_confident, intent.prompt_version) == (False, 7)+ question = self.decide.call_args.kwargs["questions"]["tab"]+ assert (question.instructions, question.criteria) == ("Which tab?", prompt.options)++ @parameterized.expand(+ [+ ("same_team_and_prompt", 7, BUNDLED_SEARCH_INTENT_PROMPT, 1),+ ("other_team", 8, BUNDLED_SEARCH_INTENT_PROMPT, 2),+ ("new_wording", 7, dataclasses.replace(BUNDLED_SEARCH_INTENT_PROMPT, instructions="Which tab?"), 2),+ ("new_threshold", 7, dataclasses.replace(BUNDLED_SEARCH_INTENT_PROMPT, confident_threshold=0.9), 2),+ ]+ )+ def test_the_same_search_is_answered_once_per_team_and_prompt(+ self, _name: str, second_team: int, second_prompt: SearchIntentPrompt, expected_calls: int+ ) -> None:+ self.decide.return_value = _answer("event_properties", 0.8)++ classify_search_intent(_search("current url"), prompt=BUNDLED_SEARCH_INTENT_PROMPT)+ classify_search_intent(_search(" current url ", team_id=second_team), prompt=second_prompt)++ assert self.decide.call_count == expected_calls+++MANAGED_OPTIONS = {"events": "An event.", "person_properties": "A person property."}+++class TestSearchIntentPrompt(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "valid",+ {"options": MANAGED_OPTIONS, "confident_threshold": 0.7},+ MANAGED_OPTIONS,+ 0.7,+ ),+ (+ "options_not_a_dict",+ {"options": ["events"], "confident_threshold": 0.7},+ BUNDLED_SEARCH_INTENT_PROMPT.options,+ 0.7,+ ),+ (+ "blank_meaning",+ {"options": {"events": " "}, "confident_threshold": 0.7},+ BUNDLED_SEARCH_INTENT_PROMPT.options,+ 0.7,+ ),+ (+ "threshold_out_of_range",+ {"options": MANAGED_OPTIONS, "confident_threshold": 60},+ MANAGED_OPTIONS,+ BUNDLED_SEARCH_INTENT_PROMPT.confident_threshold,+ ),+ (+ "more_options_than_the_gateway_takes",+ {"options": {f"tab_{i}": "A tab." for i in range(17)}, "confident_threshold": 0.7},+ BUNDLED_SEARCH_INTENT_PROMPT.options,+ 0.7,+ ),+ ("no_config", None, BUNDLED_SEARCH_INTENT_PROMPT.options, BUNDLED_SEARCH_INTENT_PROMPT.confident_threshold),+ ]+ )+ def test_a_malformed_config_part_falls_back_to_the_bundled_part(+ self, _name: str, config: dict | None, options: dict[str, str], threshold: float+ ) -> None:+ prompt = parse_search_intent_prompt(+ PromptResult(source="api", prompt="Which tab?", name="n", version=4, config=config)+ )++ assert prompt == SearchIntentPrompt(+ instructions="Which tab?", options=options, confident_threshold=threshold, version=4+ )++ def test_the_sdk_fallback_is_the_bundled_prompt(self) -> None:+ result = PromptResult(source="code_fallback", prompt=BUNDLED_SEARCH_INTENT_PROMPT.instructions)++ assert parse_search_intent_prompt(result) is BUNDLED_SEARCH_INTENT_PROMPT++ def test_a_request_never_waits_for_the_prompt_fetch(self) -> None:+ managed = dataclasses.replace(BUNDLED_SEARCH_INTENT_PROMPT, instructions="Which tab?", version=3)+ release = threading.Event()+ fetches: list[Future] = []++ def slow_fetch(**_kwargs: object) -> SearchIntentPrompt:+ assert release.wait(timeout=5)+ return managed++ refresher = _PromptRefresher()+ submit = refresher._executor.submit+ with (+ patch("posthog.taxonomic_search_intent.prompt.fetch_search_intent_prompt", slow_fetch),+ patch.object(refresher._executor, "submit", side_effect=lambda fn: fetches.append(submit(fn))),+ ):+ assert refresher.current() is BUNDLED_SEARCH_INTENT_PROMPT+ assert refresher.current() is BUNDLED_SEARCH_INTENT_PROMPT+ release.set()+ fetches[0].result(timeout=5)++ assert refresher.current() == managed+ assert len(fetches) == 1diff --git a/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py b/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.pynew file mode 100644index 000000000000..4fce2d633d02--- /dev/null+++ b/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py@@ -0,0 +1,360 @@+"""Does the decision model read a filter picker search the way the person meant it?++The unit tests in `posthog/taxonomic_search_intent/test_classify.py` feed the classifier canned answers. They cover+the value patterns, the offered tabs, the cache and the switch rule, and they pass whatever the model+says. This suite covers the model itself: given a search, the open tab and the tabs the picker shows,+does it pick a tab that holds what the person typed?++The cases come from the shapes the picker's own telemetry shows, not from any person's search:++- Most searches are a few canonical words. `email` is nearly always a person property and `url` an+ event property, and both come back empty in the events tab and the wrong property tab.+- People type the start of a word (`em`, `ur`) and a switch suggestion is only useful that early.+- The same word means a different tab on a different page: flag targeting has no event properties.++`SwitchWhenNeeded` and `NoWrongSwitch` read as the recall and the precision of the banner variant.+Precision is the number to protect: a wrong suggestion is worse than none. The question, the tab+meanings and `confident_threshold` live in the managed `taxonomic-filter-search-intent` prompt+(see `posthog/taxonomic_search_intent/prompt.py`). Score a new version here before the `production`+label moves to it, and expect the baseline to step when the prompt or the model change.++Public rather than private: the value is the comparison across runs, and every case is synthetic.++No CI job runs this suite. Run it by hand, with AI_GATEWAY_URL and AI_GATEWAY_API_KEY set for the+decision model, and with the harness's own BRAINTRUST_API_KEY and LLM_GATEWAY_ANTHROPIC_API_KEY:+ hogli evals eval_search_intent+ hogli evals eval_search_intent --eval email_in_events_tab++It scores the `production` version of the managed prompt. Set SEARCH_INTENT_PROMPT_VERSION to score+another version. Fetching it needs POSTHOG_PERSONAL_API_KEY with read access to the PostHog project;+without it the suite scores the bundled copy, and the output reports `prompt_version: None`.+"""++from __future__ import annotations++import os+import time+import asyncio+import dataclasses++from posthog.llm.system_one_client import system_one_configured+from posthog.taxonomic_search_intent.classify import SEARCH_INTENT_MODEL, classify_search_intent+from posthog.taxonomic_search_intent.contracts import SearchIntentRequest+from posthog.taxonomic_search_intent.prompt import SEARCH_INTENT_PROMPT_LABEL, fetch_search_intent_prompt++from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval+from products.posthog_ai.evals.taxonomic_filter.scorers import (+ SEARCH_INTENT_KEY,+ NoWrongSwitch,+ SearchIntentMatch,+ SwitchWhenNeeded,+)++SUITE_KIND = SuiteKind.ONE_SHOT++# The tab sets of the pickers people open most, so the model faces the choices it faces in production.+PROPERTY_FILTER = (+ "suggested_filters",+ "event_properties",+ "person_properties",+ "session_properties",+ "cohorts",+ "event_feature_flags",+ "elements",+ "pageview_urls",+ "email_addresses",+)+REPLAY_FILTER = ("suggested_filters", "events", "actions", *PROPERTY_FILTER[1:])+SERIES = ("suggested_filters", "events", "actions")+BREAKDOWN = ("event_properties", "person_properties", "session_properties", "event_feature_flags", "cohorts")+FLAG_TARGETING = ("person_properties", "cohorts", "feature_flags")+++def _case(+ name: str,+ query: str,+ *,+ active: str,+ tabs: tuple[str, ...],+ acceptable: tuple[str, ...],+ scene: str = "Insight",+) -> BaseEvalCase:+ return BaseEvalCase(+ name=name,+ prompt=query,+ metadata={"active_group_type": active, "available_group_types": list(tabs), "scene": scene},+ expected={SEARCH_INTENT_KEY: {"active": active, "acceptable": list(acceptable)}},+ )+++# The open tab cannot hold the answer. A banner helps here, and only here.+WRONG_TAB_CASES = [+ _case(+ "email_in_event_properties_tab",+ "email",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("person_properties",),+ ),+ _case(+ "email_in_events_tab",+ "email",+ active="events",+ tabs=REPLAY_FILTER,+ acceptable=("person_properties",),+ scene="Replay",+ ),+ _case(+ "url_in_person_properties_tab",+ "url",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties",),+ ),+ _case(+ "current_url_in_events_tab",+ "current url",+ active="events",+ tabs=REPLAY_FILTER,+ acceptable=("event_properties",),+ scene="Replay",+ ),+ _case(+ "utm_in_person_properties_tab",+ "utm_source",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties", "session_properties"),+ ),+ _case(+ "browser_in_person_properties_tab",+ "browser",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties",),+ ),+ _case(+ "plan_in_event_properties_tab",+ "subscription plan",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("person_properties",),+ ),+ _case(+ "session_length_in_event_properties_tab",+ "session duration",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("session_properties",),+ ),+ _case(+ "signup_in_event_properties_tab",+ "signed up",+ active="event_properties",+ tabs=REPLAY_FILTER,+ acceptable=("events",),+ scene="Replay",+ ),+ _case(+ "pageview_in_person_properties_tab",+ "pageview",+ active="person_properties",+ tabs=REPLAY_FILTER,+ acceptable=("events",),+ scene="Replay",+ ),+ _case(+ "cohort_name_in_person_properties_tab",+ "beta testers cohort",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("cohorts",),+ ),+ _case(+ "flag_in_event_properties_tab",+ "feature flag new-onboarding",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_feature_flags",),+ ),+ _case(+ "button_in_event_properties_tab",+ "sign up button",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("elements",),+ ),+]++# The open tab already holds the answer. The picker must stay quiet: any banner here is noise.+RIGHT_TAB_CASES = [+ _case(+ "email_in_person_properties_tab",+ "email",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("person_properties",),+ ),+ _case(+ "url_in_event_properties_tab",+ "url",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties",),+ ),+ # Country is on the event and on the person, and people pick either, so both count as right.+ _case(+ "country_in_event_properties_tab",+ "country",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties", "person_properties"),+ ),+ _case(+ "country_in_person_properties_tab",+ "country",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties", "person_properties"),+ ),+ _case("purchase_in_events_tab", "purchase", active="events", tabs=SERIES, acceptable=("events",)),+ _case(+ "company_in_person_properties_tab",+ "company name",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("person_properties",),+ ),+ _case(+ "channel_in_session_properties_tab",+ "channel type",+ active="session_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("session_properties",),+ ),+ _case(+ "path_in_breakdown_event_properties_tab",+ "path",+ active="event_properties",+ tabs=BREAKDOWN,+ acceptable=("event_properties",),+ ),+]++# The start of a word, a misspelling or another word for the same thing.+PARTIAL_CASES = [+ _case("email_prefix", "em", active="events", tabs=REPLAY_FILTER, acceptable=("person_properties",)),+ _case(+ "email_misspelled",+ "emial",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("person_properties",),+ ),+ _case(+ "email_hyphenated",+ "e-mail",+ active="events",+ tabs=REPLAY_FILTER,+ acceptable=("person_properties",),+ scene="Replay",+ ),+ _case(+ "url_prefix",+ "ur",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties",),+ ),+ _case(+ "page_address",+ "page address",+ active="person_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("event_properties",),+ ),+ _case("email_in_spanish", "correo", active="events", tabs=REPLAY_FILTER, acceptable=("person_properties",)),+]++# The page changes the answer: a flag's release conditions only target people.+CONTEXT_CASES = [+ _case(+ "email_in_flag_cohorts_tab",+ "email",+ active="cohorts",+ tabs=FLAG_TARGETING,+ acceptable=("person_properties",),+ scene="FeatureFlag",+ ),+ _case(+ "country_in_flag_targeting",+ "country",+ active="cohorts",+ tabs=FLAG_TARGETING,+ acceptable=("person_properties",),+ scene="FeatureFlag",+ ),+ _case(+ "entry_page_in_web_analytics",+ "entry page",+ active="event_properties",+ tabs=PROPERTY_FILTER,+ acceptable=("session_properties",),+ scene="WebAnalytics",+ ),+]+++async def eval_search_intent(ctx: EvalContext) -> None:+ # Without a gateway every case errors and scores 0, which reads as a model regression instead of a setup gap.+ if not system_one_configured():+ raise RuntimeError(+ "eval_search_intent needs AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY to reach the decision model"+ )+ version = os.environ.get("SEARCH_INTENT_PROMPT_VERSION")+ prompt = await asyncio.to_thread(+ fetch_search_intent_prompt,+ label=None if version else SEARCH_INTENT_PROMPT_LABEL,+ version=int(version) if version else None,+ )++ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ if task_ctx.demo_data is None:+ raise RuntimeError("one-shot suites run against the master Hedgebox team")+ request = SearchIntentRequest(+ team_id=task_ctx.demo_data.master_team_id,+ query=case.prompt,+ active_group_type=case.metadata["active_group_type"],+ available_group_types=tuple(case.metadata["available_group_types"]),+ scene=case.metadata["scene"],+ )+ started = time.monotonic()+ try:+ # Sync and blocking on the gateway, so keep it off the event loop. No cache: every run asks the model.+ intent = await asyncio.to_thread(classify_search_intent, request, use_cache=False, prompt=prompt)+ except Exception as error:+ return {+ "model": SEARCH_INTENT_MODEL,+ "prompt_version": prompt.version,+ "intent": None,+ "error": f"{type(error).__name__}: {error}",+ }+ answer = dataclasses.asdict(intent)+ return {+ "model": SEARCH_INTENT_MODEL,+ "prompt_version": prompt.version,+ "intent": answer,+ "latency_ms": round((time.monotonic() - started) * 1000),+ "last_message": f"{case.prompt!r} in {request.active_group_type}: {answer}",+ }++ await OneShotPublicEval(+ experiment_name="ml-inference-search-intent",+ cases=[*WRONG_TAB_CASES, *RIGHT_TAB_CASES, *PARTIAL_CASES, *CONTEXT_CASES],+ scorers=[SearchIntentMatch(), SwitchWhenNeeded(), NoWrongSwitch()],+ task=task,+ ctx=ctx,+ )diff --git a/products/posthog_ai/evals/taxonomic_filter/scorers.py b/products/posthog_ai/evals/taxonomic_filter/scorers.pynew file mode 100644index 000000000000..976fc641558e--- /dev/null+++ b/products/posthog_ai/evals/taxonomic_filter/scorers.py@@ -0,0 +1,85 @@+"""Scorers for the filter picker search intent suite.++The search intent scorers split one number, "is the answer right", into the two ways the picker can hurt+someone. A missed suggestion leaves the person where they are today. A wrong suggestion sends them to a+tab that does not hold what they typed, which is worse than no suggestion. So the switch scorers each+read as a rate over the cases they apply to, and skip (``score=None``) the rest.+"""++from __future__ import annotations++from typing import Any++from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer++SEARCH_INTENT_KEY = "search_intent"+++def _spec(expected: dict | None) -> dict[str, Any] | None:+ spec = (expected or {}).get(SEARCH_INTENT_KEY)+ return spec if isinstance(spec, dict) else None+++def _intent(output: dict | None) -> dict[str, Any]:+ return (output or {}).get("intent") or {}+++class SearchIntentMatch(Scorer):+ """Is the most likely tab one that holds what the person typed?"""++ def _name(self) -> str:+ return "search_intent_match"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected)+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})+ if output and output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})+ got = _intent(output).get("group_type")+ return Score(+ name=self._name(),+ score=1.0 if got in spec["acceptable"] else 0.0,+ metadata={"actual": got, "acceptable": spec["acceptable"], "confidence": _intent(output).get("confidence")},+ )+++class SwitchWhenNeeded(Scorer):+ """Recall: when the open tab cannot hold the answer, does the picker suggest a tab that can?"""++ def _name(self) -> str:+ return "switch_when_needed"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected)+ if spec is None or spec["active"] in spec["acceptable"]:+ return Score(name=self._name(), score=None, metadata={"reason": "The open tab is already right"})+ if output and output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": output["error"]})+ intent = _intent(output)+ helped = bool(intent.get("suggests_switch")) and intent.get("group_type") in spec["acceptable"]+ return Score(name=self._name(), score=1.0 if helped else 0.0, metadata={"intent": intent})+++class NoWrongSwitch(Scorer):+ """Precision: every suggestion the picker would show points at a tab that holds the answer.++ An erroring call shows no suggestion, which is safe, but it skips rather than passes so a broken+ classifier cannot hide behind a perfect rate.+ """++ def _name(self) -> str:+ return "no_wrong_switch"++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected)+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})+ if output and output.get("error"):+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})+ intent = _intent(output)+ if not intent.get("suggests_switch"):+ return Score(name=self._name(), score=None, metadata={"reason": "No suggestion shown"})+ # A switch away from an acceptable open tab is wrong, because the person is already in the right place.+ right = spec["active"] not in spec["acceptable"] and intent.get("group_type") in spec["acceptable"]+ return Score(name=self._name(), score=1.0 if right else 0.0, metadata={"intent": intent})diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex afc2818ea52a..5748ad09cd2a 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -533,6 +533,9 @@ tools:session-recordings-sharing-refresh-create:operation: session_recordings_sharing_refresh_createenabled: false+ taxonomic-search-intent-classify-create:+ operation: taxonomic_search_intent_classify_create+ enabled: falseuploaded-media-create:operation: uploaded_media_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b50a8d5ca607..49afb60efcc7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -89476,6 +89476,70 @@ export namespace Schemas {sdks: SdkAssessment[];}+ export interface SearchIntentRequest {+ /**+ * What the person typed into the filter picker search box.+ * @maxLength 200+ */+ query: string;+ /**+ * The picker tab that is open, as a taxonomic group type such as event_properties.+ * @maxLength 100+ */+ active_group_type: string;+ /**+ * The taxonomic group types the picker shows. The answer is always one of these, or null.+ * @maxItems 64+ * @items.maxLength 100+ */+ available_group_types: string[];+ /**+ * The id of the scene the picker is open in, such as Insight or Replay.+ * @nullable+ * @pattern ^[A-Za-z0-9_-]{1,64}$+ */+ scene?: string | null;+ }++ /**+ * * `rule` - Matched a value pattern+ * * `model` - Asked the decision model+ * * `skipped` - Not classified+ */+ export type SearchIntentSourceEnum = typeof SearchIntentSourceEnum[keyof typeof SearchIntentSourceEnum];+++ export const SearchIntentSourceEnum = {+ Rule: 'rule',+ Model: 'model',+ Skipped: 'skipped',+ } as const;++ export interface SearchIntentResponse {+ /**+ * The taxonomic group type the search most likely belongs to, or null if it was not classified.+ * @nullable+ */+ group_type: string | null;+ /** How far the chosen group stands out from the rest, from 0 (a coin flip) to 1. */+ confidence: number;+ /** Whether the confidence is high enough to act on, for example to suggest a different tab. */+ is_confident: boolean;+ /** Whether the picker should suggest switching from the open tab to group_type. */+ suggests_switch: boolean;+ /** How the answer was found: a value pattern, the decision model, or not at all.+ *+ * * `rule` - Matched a value pattern+ * * `model` - Asked the decision model+ * * `skipped` - Not classified */+ method: SearchIntentSourceEnum;+ /**+ * The version of the managed search intent prompt the model read. Null for a value pattern, a skipped search, or the bundled fallback prompt.+ * @nullable+ */+ prompt_version: number | null;+ }+export interface SearchSuggestionsQuery {/** Scope to a single scanner's observations. Defaults to every scanner you can read. */scanner_id?: string;