: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
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { LemonInputSelectOption } from '@posthog/lemon-ui'
import { getCookie } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { urls } from 'scenes/urls'
import {
getGrowthAiEnrichmentRunCreateUrl,
growthAiEnrichmentActivateCreate,
growthAiEnrichmentConfigsRetrieve,
growthAiEnrichmentLabelsRetrieve,
growthAiEnrichmentModelsRetrieve,
growthAiEnrichmentSaveCreate,
} from '../generated/api'
import type {
ConfigListResponseApi,
ConfigVersionApi,
GatewayModelListResponseApi,
LabelListResponseApi,
RunRequestApi,
SaveRequestApi,
} from '../generated/api.schemas'
import { growthAiEnrichmentRunCreateBodySampleDefault } from '../generated/api.zod'
import {
AIEnrichmentOutputField,
DEFAULT_OUTPUT_FIELD_SEED,
buildOutputFieldsPayload,
hasValidOutputFields,
} from './aiEnrichmentOutputFields'
// The run endpoint streams application/x-ndjson and isn't part of the generated response types
// (backend documents it as a raw string body) - these mirror the row/summary shapes described in
// products/growth/backend/api/ai_enrichment.py's `run` action docstring. `outputs` is keyed by the
// config's output_fields; it is null and `error` is set when that row's classification failed.
export interface AIEnrichmentRunRow {
company: string
domain: string | null
inputs: Record<string, unknown>
outputs: Record<string, boolean | number | string> | null
error?: string
// classify_payload's provenance dict (enrichment/labels.py), verbatim. `skipped` is the
// authoritative "was this row's verdict skipped" flag - prefer it over sniffing individual
// output values for the literal "unknown" string, which a schema with no boolean output
// field never writes at all (see aiEnrichmentResultColumns.ts's isSkippedRow).
meta?: { skipped?: string }
}
export interface AIEnrichmentRunSummary {
classified: number
unknown: number
errors: number
}
interface AIEnrichmentEditorSnapshot {
promptText: string
model: string
inputFields: string[]
outputFields: AIEnrichmentOutputField[]
}
const DEFAULT_MODEL = 'gpt-5-mini'
function sameInputFieldSet(a: string[], b: string[]): boolean {
if (a.length !== b.length) {
return false
}
const sortedA = [...a].sort()
const sortedB = [...b].sort()
return sortedA.every((value, index) => value === sortedB[index])
}
function sameOutputFieldSet(a: AIEnrichmentOutputField[], b: AIEnrichmentOutputField[]): boolean {
if (a.length !== b.length) {
return false
}
const normalize = (fields: AIEnrichmentOutputField[]): string =>
[...fields]
.sort((left, right) => left.key.localeCompare(right.key))
.map((field) => `${field.key}:${field.type}:${field.description}`)
.join('|')
return normalize(a) === normalize(b)
}
function safeDecodeURIComponent(value: string): string {
try {
return decodeURIComponent(value)
} catch {
// Malformed percent-encoding (e.g. a lone "%") - fall back to the raw value rather than
// crash the whole scene on an unparseable URL.
return value
}
}
function configToSnapshot(config: ConfigVersionApi): AIEnrichmentEditorSnapshot {
return {
promptText: config.prompt_text,
model: config.model,
inputFields: config.input_fields ?? [],
outputFields: (config.output_fields ?? []).map((field) => ({
key: field.key,
type: field.type,
description: field.description ?? '',
})),
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiEnrichmentLogicValues {
activateResult: ConfigVersionApi | null
activateResultLoading: boolean
activeVersion: ConfigVersionApi | null
canRun: boolean
configs: ConfigListResponseApi | null
configsLoading: boolean
editorInputFields: string[]
editorModel: string
editorOutputFields: AIEnrichmentOutputField[]
editorPromptText: string
isEditorDirty: boolean
isRunning: boolean
labels: LabelListResponseApi | null
labelsLoading: boolean
loadedSnapshot: AIEnrichmentEditorSnapshot | null
modelOptions: LemonInputSelectOption<string>[]
models: GatewayModelListResponseApi | null
modelsLoading: boolean
runError: string | null
runRows: AIEnrichmentRunRow[]
runSummary: AIEnrichmentRunSummary | null
sampleSize: number
saveResult: ConfigVersionApi | null
saveResultLoading: boolean
selectedLabel: string | null
selectedVersion: ConfigVersionApi | null
selectedVersionId: string | null
versions: ConfigVersionApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiEnrichmentLogicActions {
activateVersion: (configId: string) => string
activateVersionFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
activateVersionSuccess: (
activateResult: ConfigVersionApi,
payload?: string
) => {
activateResult: ConfigVersionApi
payload?: string
}
addOutputField: () => {
value: true
}
appendRunRow: (row: AIEnrichmentRunRow) => {
row: AIEnrichmentRunRow
}
consumeRunLine: (line: string) => {
line: string
}
loadConfigs: ({ label }: { label: string }) => {
label: string
}
loadConfigsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadConfigsSuccess: (
configs: ConfigListResponseApi,
payload?: {
label: string
}
) => {
configs: ConfigListResponseApi
payload?: {
label: string
}
}
loadLabels: () => any
loadLabelsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadLabelsSuccess: (
labels: LabelListResponseApi,
payload?: any
) => {
labels: LabelListResponseApi
payload?: any
}
loadModels: () => any
loadModelsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadModelsSuccess: (
models: GatewayModelListResponseApi,
payload?: any
) => {
models: GatewayModelListResponseApi
payload?: any
}
loadVersionIntoEditor: (config: ConfigVersionApi) => {
config: ConfigVersionApi
}
removeOutputField: (index: number) => {
index: number
}
resetRunResults: () => {
value: true
}
runClassification: () => {
value: true
}
saveVersion: (version: string) => {
version: string
}
saveVersionFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
saveVersionSuccess: (
saveResult: ConfigVersionApi,
payload?: {
version: string
}
) => {
saveResult: ConfigVersionApi
payload?: {
version: string
}
}
seedDefaultOutputFields: () => {
value: true
}
setEditorInputFields: (fields: string[]) => {
fields: string[]
}
setEditorModel: (model: string) => {
model: string
}
setEditorPromptText: (promptText: string) => {
promptText: string
}
setIsRunning: (isRunning: boolean) => {
isRunning: boolean
}
setRunError: (error: string) => {
error: string
}
setRunSummary: (summary: AIEnrichmentRunSummary) => {
summary: AIEnrichmentRunSummary
}
setSampleSize: (sampleSize: number) => {
sampleSize: number
}
setSelectedLabel: (label: string | null) => {
label: string | null
}
updateOutputField: (
index: number,
patch: Partial<AIEnrichmentOutputField>
) => {
index: number
patch: Partial<AIEnrichmentOutputField>
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiEnrichmentLogicMeta {
__keaTypeGenInternalSelectorTypes: {
versions: (configs: ConfigListResponseApi | null) => ConfigVersionApi[]
selectedVersion: (versions: ConfigVersionApi[], selectedVersionId: string | null) => ConfigVersionApi | null
activeVersion: (versions: ConfigVersionApi[]) => ConfigVersionApi | null
isEditorDirty: (
loadedSnapshot: AIEnrichmentEditorSnapshot | null,
editorPromptText: string,
editorModel: string,
editorInputFields: string[],
editorOutputFields: AIEnrichmentOutputField[]
) => boolean
canRun: (
selectedLabel: string | null,
editorPromptText: string,
editorInputFields: string[],
editorOutputFields: AIEnrichmentOutputField[],
isRunning: boolean
) => boolean
modelOptions: (
models: GatewayModelListResponseApi | null,
editorModel: string
) => LemonInputSelectOption<string>[]
}
}
export type aiEnrichmentLogicType = MakeLogicType<
aiEnrichmentLogicValues,
aiEnrichmentLogicActions,
Record<string, any>,
aiEnrichmentLogicMeta
>
export const aiEnrichmentLogic = kea<aiEnrichmentLogicType>([
path(['products', 'growth', 'frontend', 'aiEnrichment', 'aiEnrichmentLogic']),
actions({
setSelectedLabel: (label: string | null) => ({ label }),
loadVersionIntoEditor: (config: ConfigVersionApi) => ({ config }),
setEditorPromptText: (promptText: string) => ({ promptText }),
setEditorModel: (model: string) => ({ model }),
setEditorInputFields: (fields: string[]) => ({ fields }),
addOutputField: true,
removeOutputField: (index: number) => ({ index }),
updateOutputField: (index: number, patch: Partial<AIEnrichmentOutputField>) => ({ index, patch }),
seedDefaultOutputFields: true,
setSampleSize: (sampleSize: number) => ({ sampleSize }),
runClassification: true,
consumeRunLine: (line: string) => ({ line }),
appendRunRow: (row: AIEnrichmentRunRow) => ({ row }),
setRunSummary: (summary: AIEnrichmentRunSummary) => ({ summary }),
setRunError: (error: string) => ({ error }),
resetRunResults: true,
setIsRunning: (isRunning: boolean) => ({ isRunning }),
saveVersion: (version: string) => ({ version }),
}),
loaders(({ values }) => ({
labels: [
null as LabelListResponseApi | null,
{
loadLabels: async () => await growthAiEnrichmentLabelsRetrieve(),
},
],
models: [
null as GatewayModelListResponseApi | null,
{
loadModels: async () => await growthAiEnrichmentModelsRetrieve(),
},
],
configs: [
null as ConfigListResponseApi | null,
{
loadConfigs: async ({ label }: { label: string }) => await growthAiEnrichmentConfigsRetrieve({ label }),
},
],
activateResult: [
null as ConfigVersionApi | null,
{
activateVersion: async (configId: string) =>
await growthAiEnrichmentActivateCreate({ config_id: configId }),
},
],
saveResult: [
null as ConfigVersionApi | null,
{
saveVersion: async ({ version }: { version: string }) => {
if (!values.selectedLabel) {
throw new Error('Cannot save a version without a selected label.')
}
const request: SaveRequestApi = {
label: values.selectedLabel,
version: version.trim() || undefined,
prompt_text: values.editorPromptText,
model: values.editorModel,
input_fields: values.editorInputFields,
output_fields: buildOutputFieldsPayload(values.editorOutputFields),
}
return await growthAiEnrichmentSaveCreate(request)
},
},
],
})),
reducers({
selectedLabel: [
null as string | null,
{
setSelectedLabel: (_, { label }) => label,
},
],
selectedVersionId: [
null as string | null,
{
setSelectedLabel: () => null,
loadVersionIntoEditor: (_, { config }) => config.id,
activateVersionSuccess: (_, { activateResult }) => activateResult.id,
},
],
loadedSnapshot: [
null as AIEnrichmentEditorSnapshot | null,
{
setSelectedLabel: () => null,
loadVersionIntoEditor: (_, { config }) => configToSnapshot(config),
},
],
editorPromptText: [
'',
{
setSelectedLabel: () => '',
loadVersionIntoEditor: (_, { config }) => config.prompt_text,
setEditorPromptText: (_, { promptText }) => promptText,
},
],
editorModel: [
DEFAULT_MODEL as string,
{
setSelectedLabel: () => DEFAULT_MODEL as string,
loadVersionIntoEditor: (_, { config }) => config.model,
setEditorModel: (_, { model }) => model,
},
],
editorInputFields: [
[] as string[],
{
setSelectedLabel: () => [],
loadVersionIntoEditor: (_, { config }) => config.input_fields ?? [],
setEditorInputFields: (_, { fields }) => fields,
},
],
editorOutputFields: [
[] as AIEnrichmentOutputField[],
{
setSelectedLabel: () => [],
loadVersionIntoEditor: (_, { config }) => configToSnapshot(config).outputFields,
addOutputField: (state) => [...state, { key: '', type: 'boolean' as const, description: '' }],
removeOutputField: (state, { index }) => state.filter((_, existingIndex) => existingIndex !== index),
updateOutputField: (state, { index, patch }) =>
state.map((field, existingIndex) => (existingIndex === index ? { ...field, ...patch } : field)),
seedDefaultOutputFields: () => DEFAULT_OUTPUT_FIELD_SEED.map((field) => ({ ...field })),
},
],
sampleSize: [
growthAiEnrichmentRunCreateBodySampleDefault as number,
{
setSampleSize: (_, { sampleSize }) => sampleSize,
},
],
runRows: [
[] as AIEnrichmentRunRow[],
{
resetRunResults: () => [],
// A run's rows belong to the label/version it was started against - switching
// either mid-run must not keep appending the old run's rows under a new context.
setSelectedLabel: () => [],
loadVersionIntoEditor: () => [],
appendRunRow: (state, { row }) => [...state, row],
},
],
runSummary: [
null as AIEnrichmentRunSummary | null,
{
resetRunResults: () => null,
setSelectedLabel: () => null,
loadVersionIntoEditor: () => null,
setRunSummary: (_, { summary }) => summary,
},
],
// A run that fails partway through ends with a terminal {error, aborted: true} record
// instead of a summary (products/growth/backend/api/ai_enrichment.py's `run` action) -
// distinct from runSummary, which only ever reflects a run that finished.
runError: [
null as string | null,
{
resetRunResults: () => null,
setSelectedLabel: () => null,
loadVersionIntoEditor: () => null,
setRunError: (_, { error }) => error,
},
],
isRunning: [
false,
{
setIsRunning: (_, { isRunning }) => isRunning,
},
],
}),
selectors({
versions: [
(s) => [s.configs],
(configs: ConfigListResponseApi | null): ConfigVersionApi[] => configs?.results ?? [],
],
selectedVersion: [
(s) => [s.versions, s.selectedVersionId],
(versions: ConfigVersionApi[], selectedVersionId: string | null): ConfigVersionApi | null =>
versions.find((version) => version.id === selectedVersionId) ?? null,
],
// The version the batch runner actually computes right now - distinct from
// selectedVersion, which is whichever version is loaded into the editor for viewing/
// editing. Rendering "live version" off selectedVersion would show the currently viewed
// version's own string there, reading as active even while looking at a draft.
activeVersion: [
(s) => [s.versions],
(versions: ConfigVersionApi[]): ConfigVersionApi | null =>
versions.find((version) => version.is_active) ?? null,
],
isEditorDirty: [
(s) => [s.loadedSnapshot, s.editorPromptText, s.editorModel, s.editorInputFields, s.editorOutputFields],
(
loadedSnapshot: AIEnrichmentEditorSnapshot | null,
editorPromptText: string,
editorModel: string,
editorInputFields: string[],
editorOutputFields: AIEnrichmentOutputField[]
): boolean => {
if (!loadedSnapshot) {
return editorPromptText.trim().length > 0
}
return (
loadedSnapshot.promptText !== editorPromptText ||
loadedSnapshot.model !== editorModel ||
!sameInputFieldSet(loadedSnapshot.inputFields, editorInputFields) ||
!sameOutputFieldSet(loadedSnapshot.outputFields, editorOutputFields)
)
},
],
canRun: [
(s) => [s.selectedLabel, s.editorPromptText, s.editorInputFields, s.editorOutputFields, s.isRunning],
(
selectedLabel: string | null,
editorPromptText: string,
editorInputFields: string[],
editorOutputFields: AIEnrichmentOutputField[],
isRunning: boolean
): boolean =>
Boolean(selectedLabel) &&
editorPromptText.trim().length > 0 &&
editorInputFields.length > 0 &&
hasValidOutputFields(editorOutputFields) &&
!isRunning,
],
modelOptions: [
(s) => [s.models, s.editorModel],
(models: GatewayModelListResponseApi | null, editorModel: string): LemonInputSelectOption<string>[] => {
const ids = new Set(models ? models.results.map((model) => model.id) : [])
if (editorModel) {
ids.add(editorModel)
}
return Array.from(ids)
.sort()
.map((id) => ({ key: id, label: id }))
},
],
}),
listeners(({ actions, values, cache }) => {
// Rows in flight belong to whatever label/version the run was started against - switching
// either must stop that stream rather than let it keep writing into a now-stale context.
// The reducers above already clear runRows/runSummary on the same actions; this is the
// half that actually cancels the network work and its in-flight-guard state.
const stopRunIfInFlight = (): void => {
cache.disposables.dispose('aiEnrichmentRunStream')
if (values.isRunning) {
actions.setIsRunning(false)
}
}
return {
setSelectedLabel: ({ label }) => {
stopRunIfInFlight()
if (label) {
actions.loadConfigs({ label })
}
},
loadVersionIntoEditor: () => {
stopRunIfInFlight()
},
loadLabelsSuccess: ({ labels }) => {
// Auto-enter the only label so the picker is skipped when there's nothing to pick.
if (!values.selectedLabel && labels && labels.results.length === 1) {
router.actions.replace(urls.aiEnrichment(labels.results[0].label))
}
},
loadConfigsSuccess: ({ configs }) => {
const versions = configs?.results ?? []
if (versions.length === 0) {
return
}
const pendingId = cache.pendingSelectAfterSaveId as string | null | undefined
cache.pendingSelectAfterSaveId = null
// Default to what's actually running in production, not the newest draft - a fresh
// page load should show the active version unless the caller just saved something else.
const target =
(pendingId && versions.find((version) => version.id === pendingId)) ||
versions.find((version) => version.is_active) ||
versions[0]
actions.loadVersionIntoEditor(target)
},
activateVersionSuccess: ({ activateResult }) => {
lemonToast.success(`Activated version ${activateResult.version}.`)
if (values.selectedLabel) {
actions.loadConfigs({ label: values.selectedLabel })
}
},
activateVersionFailure: () => {
lemonToast.error('Failed to activate this version.')
},
saveVersionSuccess: ({ saveResult }) => {
lemonToast.success(`Saved version ${saveResult.version}.`)
cache.pendingSelectAfterSaveId = saveResult.id
if (values.selectedLabel) {
actions.loadConfigs({ label: values.selectedLabel })
}
},
saveVersionFailure: ({ error }) => {
lemonToast.error(error || 'Failed to save this version.')
},
runClassification: async () => {
if (!values.selectedLabel || !values.editorPromptText.trim()) {
return
}
actions.resetRunResults()
actions.setIsRunning(true)
const controller = new AbortController()
// The run can take a while (one LLM call per sampled org); it should keep streaming
// even if the staff user switches tabs, so opt out of the disposables plugin's
// pause-on-hidden behavior. Re-adding under the same key aborts any prior in-flight
// run before starting a new one.
cache.disposables.add(() => () => controller.abort(), 'aiEnrichmentRunStream', {
pauseOnPageHidden: false,
})
try {
const requestBody: RunRequestApi = {
label: values.selectedLabel,
prompt_text: values.editorPromptText,
model: values.editorModel,
input_fields: values.editorInputFields,
output_fields: buildOutputFieldsPayload(values.editorOutputFields),
sample: values.sampleSize,
}
// The generated client (growthAiEnrichmentRunCreate) can't stream - it routes
// through lib/api, which buffers/parses the body as JSON. Only the URL builder is
// reusable here; the fetch itself has to be hand-rolled to read the body as it
// arrives.
const response = await fetch(getGrowthAiEnrichmentRunCreateUrl(), {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
Accept: 'application/x-ndjson',
'X-CSRFToken': getCookie('posthog_csrftoken') || '',
},
body: JSON.stringify(requestBody),
signal: controller.signal,
})
if (!response.ok || !response.body) {
// Surface the server's own message: sample bounds and output-field key errors
// both land here, and this is a debugging tool.
const detail = await response
.json()
.then((body) => body?.detail)
.catch(() => undefined)
throw new Error(detail || `Test run failed with status ${response.status}`)
}
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (value) {
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() ?? ''
for (const line of lines) {
actions.consumeRunLine(line)
}
}
if (done) {
// Flush the decoder: a stream ending mid-multibyte sequence otherwise
// drops its trailing character, and company names are routinely non-ASCII.
buffer += decoder.decode()
if (buffer.trim()) {
actions.consumeRunLine(buffer)
}
break
}
}
// The response is a 200 the moment streaming starts, so the only signal that a run
// finished rather than died partway is the summary line the backend ends with -
// unless it ended with a terminal error record instead, which consumeRunLine
// already turned into runError and is shown in the results area below. Only
// fall back to this generic toast when neither arrived.
if (!values.runSummary && !values.runError) {
lemonToast.error('Test run stopped before finishing. Some rows may be missing.')
}
} catch (e) {
if (!(e instanceof DOMException && e.name === 'AbortError')) {
lemonToast.error(e instanceof Error ? e.message : 'Test run failed.')
}
} finally {
actions.setIsRunning(false)
cache.disposables.dispose('aiEnrichmentRunStream')
}
},
consumeRunLine: ({ line }) => {
const trimmed = line.trim()
if (!trimmed) {
return
}
try {
const parsed = JSON.parse(trimmed)
if (parsed && typeof parsed === 'object') {
if ('summary' in parsed && parsed.summary) {
actions.setRunSummary(parsed.summary as AIEnrichmentRunSummary)
return
}
// A run that fails partway ends with this terminal record instead of a
// summary - it must be surfaced (see runError/AIEnrichmentResultsTable),
// not silently dropped just because it isn't a row.
if ('error' in parsed && parsed.aborted) {
actions.setRunError(String(parsed.error))
return
}
if ('outputs' in parsed) {
actions.appendRunRow(parsed as AIEnrichmentRunRow)
}
}
} catch {
// Defensive: each ndjson line is parsed independently, so a malformed or
// unexpectedly-split line is skipped instead of aborting the whole run.
}
},
}
}),
afterMount(({ actions }) => {
actions.loadLabels()
actions.loadModels()
}),
urlToAction(({ actions, values }) => ({
'/ai-enrichment': () => {
if (values.selectedLabel !== null) {
actions.setSelectedLabel(null)
}
},
'/ai-enrichment/:label': ({ label }) => {
if (!label) {
return
}
// manifest.tsx's urls.aiEnrichment() encodeURIComponents the label when building the
// URL; kea-router (url-pattern under the hood) does not decode path params on the way
// back out, so this is the other half of that round trip.
const decodedLabel = safeDecodeURIComponent(label)
if (decodedLabel !== values.selectedLabel) {
actions.setSelectedLabel(decodedLabel)
}
},
})),
])