: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(growth): ai enrichment lab - edit, test-run, and switch classifier versions (#75754)
Matt Brooker685374c3f956
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 66cc9ba3750d..18c18b455f67 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -91,6 +91,7 @@ export const productScenes: Record<string, () => Promise<any>> = {Game368Hedgehogs: () => import('../../products/games/368Hedgehogs/368Hedgehogs'),FlappyHog: () => import('../../products/games/FlappyHog/FlappyHog'),IdentityMatching: () => import('../../products/growth/frontend/IdentityMatchingScene'),+ AIEnrichment: () => import('../../products/growth/frontend/aiEnrichment/AIEnrichmentScene'),LegalDocuments: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentsScene'),LegalDocumentNew: () => import('../../products/legal_documents/frontend/scenes/LegalDocumentNewScene'),Links: () => import('../../products/links/frontend/LinksScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 7971dffb8b0d..f5b8c1ba8c32 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -164,6 +164,8 @@ export const productRoutes: Record<string, [string, string]> = {'/games/368hedgehogs': ['Game368Hedgehogs', 'game368Hedgehogs'],'/games/flappyhog': ['FlappyHog', 'flappyHog'],'/identity-matching': ['IdentityMatching', 'identityMatching'],+ '/ai-enrichment': ['AIEnrichment', 'aiEnrichment'],+ '/ai-enrichment/:label': ['AIEnrichment', 'aiEnrichment'],'/legal': ['LegalDocuments', 'legalDocuments'],'/legal/new/:type': ['LegalDocumentNew', 'legalDocumentNew'],'/links': ['Links', 'links'],@@ -678,6 +680,7 @@ export const productConfiguration: Record<string, any> = {'Review probable links between anonymous visitors and identified persons, recovered from first-party signals.',iconType: 'persons',},+ AIEnrichment: { name: 'AI enrichment', instanceLevel: true },LegalDocuments: {name: 'Legal documents',organizationBased: true,@@ -1245,6 +1248,7 @@ export const productUrls = {group: (groupTypeIndex: string | number, groupKey: string, encode: boolean = true, tab?: string | null): string =>`/groups/${groupTypeIndex}/${encode ? encodeURIComponent(groupKey) : groupKey}${tab ? `/${tab}` : ''}`,identityMatching: (): string => '/identity-matching',+ aiEnrichment: (label?: string): string => `/ai-enrichment${label ? `/${encodeURIComponent(label)}` : ''}`,legalDocuments: (): string => '/legal',legalDocumentNew: (type: 'BAA' | 'DPA'): string => `/legal/new/${type.toLowerCase()}`,links: (): string => '/links',@@ -2082,7 +2086,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [tags: ['alpha'],iconType: 'persons',sceneKey: 'IdentityMatching',- sceneKeys: ['IdentityMatching'],+ sceneKeys: ['IdentityMatching', 'AIEnrichment'],},{path: 'LLM analytics',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 02cec4ff0119..b42675722128 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3283,12 +3283,25 @@ importers:kea-loaders:specifier: 'catalog:'version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-router:+ specifier: 'catalog:'+ version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))react:specifier: 18.3.1version: 18.3.1typescript:specifier: 6.0.3version: 6.0.3+ devDependencies:+ '@testing-library/jest-dom':+ specifier: ^5.17.0+ version: 5.17.0+ '@testing-library/react':+ specifier: ^14.3.1+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))products/legal_documents:dependencies:diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 7cb70c6ade8c..27a234eae98c 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -32,7 +32,10 @@ import pendulum # noqa F401import sqlparsefrom clickhouse_pool import ChPoolfrom clickhouse_pool.pool import TooManyConnections-from rest_framework.test import APITestCase as DRFTestCase+from rest_framework.test import (+ APITestCase as DRFTestCase,+ APITransactionTestCase,+)from syrupy.extensions.amber import AmberSnapshotExtensionfrom posthog.hogql import (@@ -1111,6 +1114,39 @@ class APIBaseTest(PostHogTestCase, ErrorResponsesMixin, DRFTestCase):yield+class NonAtomicAPIBaseTest(PostHogTestCase, ErrorResponsesMixin, APITransactionTestCase):+ """Like APIBaseTest, but on TransactionTestCase (via DRF's APITransactionTestCase) rather+ than TestCase - for endpoints that hand work to real worker threads which must see this+ test's own DB writes. TestCase wraps each test in an outer, never-committed transaction that+ only the test's own connection can see; a worker thread opens its own connection and a fresh+ query on it finds no such row at all, not a stale one. See NonAtomicBaseTest for the same+ trade-off outside DRF, and its docstring's link for background.+ """++ @classmethod+ def setUpClass(cls):+ cls.setUpTestData()++ def setUp(self):+ super().setUp()++ cache.clear()+ TEST_clear_instance_license_cache()+ rate_limit.is_rate_limit_enabled.cache_clear()+ rate_limit.get_team_allow_list.cache_clear()++ if self.CONFIG_AUTO_LOGIN and self.user:+ self.client.force_login(self.user)++ def _fixture_teardown(self):+ for db_name in cast(Any, self)._databases_names(include_mirrors=False):+ try:+ _selective_flush(db_name, reset_sequences=True)+ except Exception:+ logger.exception("Selective flush of %r failed; falling back to the stock flush command", db_name)+ call_command("flush", verbosity=0, interactive=False, database=db_name, allow_cascade=True)++def stripResponse(response, remove=("action", "label", "persons_urls", "filter")):if len(response):for attr in remove:diff --git a/products/growth/backend/api/ai_enrichment.py b/products/growth/backend/api/ai_enrichment.pynew file mode 100644index 000000000000..92801db8eff9--- /dev/null+++ b/products/growth/backend/api/ai_enrichment.py@@ -0,0 +1,378 @@+"""Staff-only DRF API for the enrichment "AI enrichment": list labels, list a label's prompt+config versions, create a new immutable version, test-run a draft config against recent+archived orgs, and flip which version is active.++Shaped around config version + input rows + verdict rows, not around enrichment orgs, so the+same contract can host a future team-scoped customer-facing product without a rewrite. save/run+reuse the classification runner in products.growth.backend.enrichment.lab - the same module the+batch runner is built on - so a test run and a shadow run can never drift on how a verdict is+computed.++Serializers live in ai_enrichment_serializers.py.+"""++import re+import json+from collections.abc import AsyncIterator+from typing import Any, cast++from django.db import IntegrityError, transaction+from django.db.models import Count+from django.http.response import HttpResponseBase++import structlog+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import renderers, request, response, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import NotFound+from rest_framework.permissions import IsAuthenticated+from rest_framework.throttling import UserRateThrottle++from posthog.api.mixins import validated_request+from posthog.api.streaming import streaming_response+from posthog.api.utils import ErrorResponseSerializer+from posthog.exceptions import Conflict+from posthog.exceptions_capture import capture_exception+from posthog.helpers.impersonation import is_impersonated+from posthog.llm.gateway_client import get_llm_client+from posthog.models import User+from posthog.permissions import IsStaffUser+from posthog.renderers import SafeJSONRenderer++from products.growth.backend.api.ai_enrichment_serializers import (+ ActivateRequestSerializer,+ ConfigListResponseSerializer,+ ConfigsQuerySerializer,+ ConfigVersionSerializer,+ GatewayModelListResponseSerializer,+ LabelListResponseSerializer,+ RunRequestSerializer,+ SaveRequestSerializer,+)+from products.growth.backend.enrichment.lab import (+ DRAFT_VERSION_SENTINEL,+ MAX_SAMPLE_SIZE,+ format_run_row,+ list_gateway_models,+ stream_run_classifications,+)+from products.growth.backend.enrichment.labels import (+ UNKNOWN,+ recent_latest_fetches_qs,+ signup_domain_for_organization,+ verdict_field_key,+)+from products.growth.backend.models import EnrichmentLabelResult, EnrichmentPromptConfig, OrganizationEnrichmentFetch++logger = structlog.get_logger(__name__)++# Server-assigned version identity. Matched anywhere in the string (not anchored), so a legacy+# hand-written version like "ai-pilled-clay-v1" still contributes its 1 - only a label with no+# v<n> pattern in any version at all falls back to the row count.+_VERSION_SUFFIX_RE = re.compile(r"v(\d+)")+++def _next_version(label: str) -> str:+ """The label's next `v<n>`, from the highest `v<digits>` occurring anywhere in any existing+ version string for this label, plus one - not a row count, and not an anchored match.++ Counting recycles a version string after any row is removed, which would silently+ reattribute every verdict stamped with it to a prompt that never produced it. Falls back to+ one past the row count only when nothing on record has a v<n> pattern at all, since there's+ no numeric precedent to bump. Must be called inside a transaction: the row lock is what stops+ two concurrent saves picking the same n.+ """+ existing = list(EnrichmentPromptConfig.objects.select_for_update().filter(name=label))+ matches = [match for config in existing for match in _VERSION_SUFFIX_RE.finditer(config.version)]+ if matches:+ return f"v{max(int(match.group(1)) for match in matches) + 1}"+ return f"v{len(existing) + 1}"+++def _build_run_inputs(sample: int) -> list[tuple[OrganizationEnrichmentFetch, str | None]]:+ """All the ORM work a run needs, done up front on the request thread: workers only make LLM+ calls (see stream_run_classifications), so no query runs mid-stream. Only orgs with AI+ processing consent are eligible - the same gate the batch runner and dry-run command apply+ per row (enrichment_label_batch.py, enrichment_label_dry_run.py via ai_processing_approved).+ This is a coarse first pass, not the last word: `=True` also excludes the nullable column's+ unset (NULL) state, matching ai_processing_approved's "only an explicit True approves", but a+ run can still stream for seconds to minutes, long enough for consent to be revoked after this+ filter runs - classify_fetch_for_run (enrichment/lab.py) rechecks per row immediately before+ each classification for that reason.+ """+ fetches = list(+ recent_latest_fetches_qs()+ .filter(organization__is_ai_data_processing_approved=True)+ .select_related("organization")[:sample]+ )+ return [(fetch, signup_domain_for_organization(fetch.organization)) for fetch in fetches]+++class NDJSONRenderer(renderers.BaseRenderer):+ """Content-negotiation stand-in for the streamed run endpoint: the stream is built by+ the view itself, so render() only ever sees error payloads from exception handling.++ Declared on the `run` @action only (never renderer_classes on the whole viewset) - putting it+ viewset-wide previously broke drf-spectacular codegen for every other endpoint on this+ viewset.+ """++ media_type = "application/x-ndjson"+ format = "ndjson"++ def render(self, data: Any, accepted_media_type: str | None = None, renderer_context: Any = None) -> bytes:+ return json.dumps(data).encode()+++class AIEnrichmentRunThrottle(UserRateThrottle):+ """The global throttles are PersonalApiKeyRateThrottle subclasses, which pass straight through+ for a session-authenticated request with no personal API key - so this endpoint would otherwise+ have no limit at all. Each allowed call can cost up to MAX_SAMPLE_SIZE LLM completions."""++ scope = "ai_enrichment_run"+ rate = "10/min"+++class AIEnrichmentViewSet(viewsets.ViewSet):+ """+ Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ config versions, test-run a draft config against recently archived orgs, save a new+ immutable version, and flip which version is active.++ Registered on the root router so it is not team-nested - prompt configs are instance-global,+ not scoped to any team or org.+ """++ # Not part of the public API scope model: access is gated entirely by IsStaffUser below,+ # not by a personal-API-key scope, so this stays out of the public OpenAPI/generated-client+ # surface (see posthog/api/documentation.py's INTERNAL handling).+ scope_object = "INTERNAL"+ permission_classes = [IsAuthenticated, IsStaffUser]++ @validated_request(responses={200: OpenApiResponse(response=LabelListResponseSerializer)})+ @action(methods=["GET"], detail=False)+ def labels(self, request: request.Request, **kwargs: Any) -> response.Response:+ counts = EnrichmentPromptConfig.objects.values("name").annotate(version_count=Count("id")).order_by("name")+ active_version_by_label = dict(+ EnrichmentPromptConfig.objects.filter(is_active=True).values_list("name", "version")+ )+ results = [+ {+ "label": row["name"],+ "version_count": row["version_count"],+ "active_version": active_version_by_label.get(row["name"]),+ }+ for row in counts+ ]+ return response.Response(LabelListResponseSerializer({"results": results}).data)++ @validated_request(responses={200: OpenApiResponse(response=GatewayModelListResponseSerializer)})+ @action(methods=["GET"], detail=False)+ def models(self, request: request.Request, **kwargs: Any) -> response.Response:+ results = [{"id": model_id} for model_id in list_gateway_models()]+ return response.Response(GatewayModelListResponseSerializer({"results": results}).data)++ @validated_request(+ query_serializer=ConfigsQuerySerializer,+ responses={200: OpenApiResponse(response=ConfigListResponseSerializer)},+ )+ @action(methods=["GET"], detail=False)+ def configs(self, request: request.Request, **kwargs: Any) -> response.Response:+ label = request.validated_query_data["label"]+ versions = list(+ EnrichmentPromptConfig.objects.filter(name=label).select_related("created_by").order_by("-created_at")+ )+ versions_with_results = set(+ EnrichmentLabelResult.objects.filter(+ label_name=label, prompt_version__in=[version.version for version in versions]+ )+ .values_list("prompt_version", flat=True)+ .distinct()+ )+ # Pass raw model instances through the outer wrapper so its nested `results =+ # ConfigVersionSerializer(many=True)` field does the serialization exactly once - the+ # SerializerMethodFields below read model attributes (e.g. obj.version) and would break+ # on a second pass over already-serialized dicts.+ serializer = ConfigListResponseSerializer(+ {"results": versions}, context={"versions_with_results": versions_with_results}+ )+ return response.Response(serializer.data)++ @extend_schema(+ request=RunRequestSerializer,+ responses={(200, "application/x-ndjson"): OpenApiTypes.STR},+ summary="Stream classifier verdicts for an unsaved draft config against recently archived orgs.",+ description="One JSON object per line: a {company, domain, inputs, outputs: {<key>: value, ...}, meta} row "+ "as each LLM call completes, keyed by the submitted output_fields, then a final "+ "{summary: {classified, unknown, errors}} line. A run that fails partway ends with "+ "{error, aborted: true} instead of a summary. Persists nothing - spends real LLM money, so sample is "+ f"capped at {MAX_SAMPLE_SIZE} and the endpoint is rate limited.",+ )+ @action(+ methods=["POST"],+ detail=False,+ throttle_classes=[AIEnrichmentRunThrottle],+ renderer_classes=[SafeJSONRenderer, NDJSONRenderer],+ )+ def run(self, request: request.Request, **kwargs: Any) -> HttpResponseBase:+ serializer = RunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data++ # Unsaved on purpose: the run classifies against whatever the caller submitted, nothing+ # is persisted, and DRAFT_VERSION_SENTINEL never collides with a real saved version+ # string - SaveRequestSerializer separately rejects it as a caller-supplied version.+ draft_config = EnrichmentPromptConfig(+ name=data["label"],+ version=DRAFT_VERSION_SENTINEL,+ prompt_text=data["prompt_text"],+ model=data["model"],+ input_fields=data["input_fields"],+ output_fields=data["output_fields"],+ )++ items = _build_run_inputs(data["sample"])+ # tenacity in labels.py already owns retries (classify_payload's _call_and_parse,+ # stop_after_attempt(3)); the SDK's own internal retries underneath would multiply that+ # budget several-fold per fetch and actively worsen a 429 the tenacity layer is already+ # backing off from.+ client = get_llm_client(product="growth").with_options(max_retries=0)++ logger.info(+ "growth_ai_enrichment_run",+ staff_user_id=request.user.id,+ was_impersonated=is_impersonated(request),+ label=data["label"],+ model=data["model"],+ sample_requested=data["sample"],+ sample_matched=len(items),+ )++ verdict_key = verdict_field_key(draft_config)+ label = data["label"]++ # No ORM work happens inside the stream (items are prefetched above), so the+ # request-thread connections can be released before streaming starts.+ async def _stream() -> AsyncIterator[bytes]:+ classified = unknown = errors = 0+ try:+ async for company, domain, output, error, inputs in stream_run_classifications(+ draft_config, items, client+ ):+ if error is not None:+ errors += 1+ elif verdict_key is not None and output is not None and output.get(verdict_key) == UNKNOWN:+ unknown += 1+ else:+ classified += 1+ row = format_run_row(draft_config, company, domain, output, error, inputs)+ yield (json.dumps(row) + "\n").encode()+ except Exception as e:+ # The response is already 200 with rows sent, so the only way to tell the client+ # apart from a completed run is a terminal line it can look for.+ capture_exception(e, {"label": label, "path": "ai_enrichment.run"})+ yield (json.dumps({"error": f"{type(e).__name__}: run failed", "aborted": True}) + "\n").encode()+ return+ logger.info(+ "growth_ai_enrichment_run_complete",+ label=label,+ model=draft_config.model,+ classified=classified,+ unknown=unknown,+ errors=errors,+ )+ summary = {"summary": {"classified": classified, "unknown": unknown, "errors": errors}}+ yield (json.dumps(summary) + "\n").encode()++ return streaming_response(_stream(), content_type="application/x-ndjson")++ @validated_request(+ request_serializer=SaveRequestSerializer,+ responses={+ 201: OpenApiResponse(response=ConfigVersionSerializer),+ 409: OpenApiResponse(+ response=ErrorResponseSerializer, description="A concurrent save took this version. Retry."+ ),+ },+ )+ @action(methods=["POST"], detail=False)+ def save(self, request: request.Request, **kwargs: Any) -> response.Response:+ data = request.validated_data+ label = data["label"]+ requested_version = data.get("version", "").strip()+ try:+ # IsAuthenticated + IsStaffUser guarantee a real User here.+ with transaction.atomic():+ # Only the server-suggestion path needs the row lock (it reads sibling versions+ # to pick the next one) - a caller-supplied version relies on the unique+ # constraint alone and needs no lock.+ version = requested_version or _next_version(label)+ config = EnrichmentPromptConfig.objects.create(+ name=label,+ version=version,+ prompt_text=data["prompt_text"],+ model=data["model"],+ input_fields=data["input_fields"],+ output_fields=data["output_fields"],+ is_active=False,+ created_by=cast(User, request.user),+ )+ except IntegrityError:+ # A brand-new label has no rows for _next_version to lock, so two concurrent first+ # saves can both pick v1; a caller-supplied version can just as easily collide.+ # Retrying is the caller's move; this must not be a 500.+ raise Conflict("A version with this name already exists for this label. Try a different one.")++ logger.info(+ "growth_ai_enrichment_save",+ staff_user_id=request.user.id,+ was_impersonated=is_impersonated(request),+ label=config.name,+ version=config.version,+ )++ serializer = ConfigVersionSerializer(config, context={"versions_with_results": set()})+ return response.Response(serializer.data, status=status.HTTP_201_CREATED)++ @validated_request(+ request_serializer=ActivateRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ConfigVersionSerializer),+ 404: OpenApiResponse(response=ErrorResponseSerializer, description="Config not found."),+ },+ )+ @action(methods=["POST"], detail=False)+ def activate(self, request: request.Request, **kwargs: Any) -> response.Response:+ config_id = request.validated_data["config_id"]+ # The label is read under the row lock, not before it: a rename committing between the+ # read and the transaction would target the deactivation at the retired name, match no+ # siblings, and leave two rows active under the new one - which the partial unique+ # constraint growth_prompt_config_one_active then rejects as a 500.+ with transaction.atomic():+ config = EnrichmentPromptConfig.objects.select_for_update().filter(pk=config_id).first()+ if config is None:+ raise NotFound(f"Config {config_id} not found.")+ # Deactivate first, then activate, so the constraint only ever sees at most one+ # active row per label.+ EnrichmentPromptConfig.objects.filter(name=config.name, is_active=True).exclude(pk=config.pk).update(+ is_active=False+ )+ config.is_active = True+ config.save(update_fields=["is_active"])++ logger.info(+ "growth_ai_enrichment_activate",+ staff_user_id=request.user.id,+ was_impersonated=is_impersonated(request),+ label=config.name,+ version=config.version,+ )++ has_results = EnrichmentLabelResult.objects.filter(+ label_name=config.name, prompt_version=config.version+ ).exists()+ serializer = ConfigVersionSerializer(+ config, context={"versions_with_results": {config.version} if has_results else set()}+ )+ return response.Response(serializer.data)diff --git a/products/growth/backend/api/ai_enrichment_serializers.py b/products/growth/backend/api/ai_enrichment_serializers.pynew file mode 100644index 000000000000..7f90c776f841--- /dev/null+++ b/products/growth/backend/api/ai_enrichment_serializers.py@@ -0,0 +1,243 @@+"""Request and response serializers for the staff AI enrichment API (see ai_enrichment.py).++These are the source of truth for the generated frontend types and MCP tool schemas, so every+field carries help_text and every response shape is a declared serializer rather than a raw dict.+"""++from typing import Any++from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from rest_framework import serializers++from posthog.exceptions_capture import capture_exception++from products.growth.backend.enrichment.lab import DEFAULT_SAMPLE_SIZE, DRAFT_VERSION_SENTINEL, MAX_SAMPLE_SIZE+from products.growth.backend.enrichment.labels import (+ MAX_OUTPUT_FIELD_DESCRIPTION_CHARS,+ MAX_OUTPUT_FIELDS,+ MAX_PROMPT_TEXT_CHARS,+ OUTPUT_FIELD_KEY_RE,+ OUTPUT_FIELD_TYPES,+ RESERVED_OUTPUT_FIELD_KEYS,+ PromptConfigError,+ validate_input_fields,+ validate_output_fields,+)+from products.growth.backend.models import EnrichmentPromptConfig++_OUTPUT_FIELDS_HELP = (+ "Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the "+ "classifier's entire output contract - the label is a human name and is never an output key, so renaming a "+ "label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not "+ f"be 'meta' or 'inputs'. At most {MAX_OUTPUT_FIELDS} fields."+)++_PROMPT_TEXT_HELP = (+ "System prompt; {email} is replaced with the signup email domain at runtime. "+ f"At most {MAX_PROMPT_TEXT_CHARS} characters."+)++_MODEL_HELP = "Gateway model to classify with, routed through the LLM gateway. See GET /models/ for what it serves."++_INPUT_FIELDS_HELP = (+ "Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected "+ "value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional."+)+++class OutputFieldSerializer(serializers.Serializer):+ key = serializers.RegexField(+ OUTPUT_FIELD_KEY_RE,+ help_text="Output key, e.g. ai_pilled. Lowercase, starts with a letter, letters/digits/underscore only.",+ )+ type = serializers.ChoiceField(+ choices=[(value, value) for value in OUTPUT_FIELD_TYPES],+ help_text="Value type the LLM must return for this key.",+ )+ description = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=MAX_OUTPUT_FIELD_DESCRIPTION_CHARS,+ help_text=f"Shown to the LLM to describe what this key means. At most {MAX_OUTPUT_FIELD_DESCRIPTION_CHARS} "+ "characters.",+ )++ def validate_key(self, value: str) -> str:+ if value in RESERVED_OUTPUT_FIELD_KEYS:+ raise serializers.ValidationError(f"{value!r} is reserved for provenance and cannot be an output key.")+ return value+++def _validate_output_fields_list(value: list[dict[str, str]]) -> list[dict[str, str]]:+ """The two rules OutputFieldSerializer cannot enforce per item: uniqueness across the list,+ and a cap on the list's own length (unlike max_length on a single field, list-item-count+ limits aren't expressible on a `many=True` nested serializer)."""+ if len(value) > MAX_OUTPUT_FIELDS:+ raise serializers.ValidationError(f"At most {MAX_OUTPUT_FIELDS} output fields are allowed, got {len(value)}.")+ keys = [field["key"] for field in value]+ duplicates = {key for key in keys if keys.count(key) > 1}+ if duplicates:+ raise serializers.ValidationError(f"Duplicate output field key {sorted(duplicates)[0]!r}.")+ return value+++def _validate_config_shape(attrs: dict[str, Any], *, capture_path: str | None = None) -> None:+ """Run validate_input_fields/validate_output_fields (enrichment/labels.py) against a+ throwaway, unsaved config built from the submitted shape, translating a PromptConfigError+ into a normal 400 instead of it surfacing as an unhandled 500 - or, on the streaming /run/+ endpoint, only after a 200 response has already started.++ capture_path is set only by the money-spending /run/ endpoint's serializer: a bad draft+ config there means a request was about to reach the LLM gateway, which is worth tracking+ even though it's "just" a 400. Plain save-time validation errors are routine user input and+ don't need capture_exception, matching how ActivateRequestSerializer/RenameRequestSerializer+ style 400s are handled elsewhere in this file.+ """+ draft = EnrichmentPromptConfig(+ name=attrs.get("label", ""),+ prompt_text=attrs.get("prompt_text", ""),+ model=attrs.get("model", ""),+ input_fields=attrs.get("input_fields", []),+ output_fields=attrs["output_fields"],+ )+ try:+ validate_input_fields(draft)+ validate_output_fields(draft)+ except PromptConfigError as e:+ if capture_path is not None:+ capture_exception(e, {"path": capture_path})+ raise serializers.ValidationError(str(e)) from e+++class LabelSummarySerializer(serializers.Serializer):+ label = serializers.CharField(help_text="Label name computed by one or more prompt config versions.") # type: ignore[assignment] # DRF Field.label collides with a field named label+ version_count = serializers.IntegerField(help_text="Number of prompt config versions saved for this label.")+ active_version = serializers.CharField(+ allow_null=True, help_text="Version string the batch runner currently computes for this label, or null."+ )+++@extend_schema_serializer(many=False)+class LabelListResponseSerializer(serializers.Serializer):+ results = LabelSummarySerializer(many=True, help_text="Distinct labels, alphabetical.")+++class ConfigVersionSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Prompt config row id.")+ name = serializers.CharField(help_text="Label this config computes, e.g. ai_pilled.")+ version = serializers.CharField(help_text="Server-assigned version identity, e.g. v3.")+ prompt_text = serializers.CharField(help_text=_PROMPT_TEXT_HELP)+ model = serializers.CharField(help_text="Gateway model id this version was authored against.")+ input_fields = serializers.ListField(child=serializers.CharField(), help_text=_INPUT_FIELDS_HELP)+ output_fields = OutputFieldSerializer(many=True, help_text=_OUTPUT_FIELDS_HELP)+ is_active = serializers.BooleanField(help_text="Whether the batch runner currently computes this version.")+ created_by_email = serializers.SerializerMethodField(+ help_text="Email of the staff user who created this version, or null for system-seeded rows."+ )+ created_at = serializers.DateTimeField(help_text="When this version was created.")+ has_results = serializers.SerializerMethodField(+ help_text="Whether any EnrichmentLabelResult rows reference this version. Informational only: the API "+ "never edits a version's content in place, it only creates a new one, so this doesn't gate anything. "+ "The label name is not part of a version's content and can always be renamed."+ )++ @extend_schema_field(serializers.EmailField(allow_null=True))+ def get_created_by_email(self, obj: EnrichmentPromptConfig) -> str | None:+ return obj.created_by.email if obj.created_by else None++ @extend_schema_field(serializers.BooleanField())+ def get_has_results(self, obj: EnrichmentPromptConfig) -> bool:+ return obj.version in self.context.get("versions_with_results", set())+++@extend_schema_serializer(many=False)+class ConfigListResponseSerializer(serializers.Serializer):+ results = ConfigVersionSerializer(many=True, help_text="Versions for the requested label, newest first.")+++class ConfigsQuerySerializer(serializers.Serializer):+ label = serializers.CharField(help_text="Label name to list prompt config versions for.") # type: ignore[assignment] # DRF Field.label collides with a field named label+++class ActivateRequestSerializer(serializers.Serializer):+ config_id = serializers.UUIDField(help_text="Prompt config id to activate for its label.")+++class GatewayModelSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Gateway model id, usable as `model` on save/run.")+++@extend_schema_serializer(many=False)+class GatewayModelListResponseSerializer(serializers.Serializer):+ results = GatewayModelSerializer(+ many=True,+ help_text="Models the gateway currently lists (cached for 5 minutes), or empty if it is unreachable - "+ "there is no curated mirror, since one goes stale silently.",+ )+++class SaveRequestSerializer(serializers.Serializer):+ label = serializers.CharField(max_length=128, help_text="Label this config computes, e.g. ai_pilled.") # type: ignore[assignment] # DRF Field.label collides with a field named label+ version = serializers.CharField(+ max_length=128,+ required=False,+ allow_blank=True,+ help_text="Version identity for the new row, e.g. v3. Optional: omit (or send blank) to accept the "+ "server-suggested next version for this label. Versions are immutable once created - there is no "+ "update endpoint - and (label, version) must be unique.",+ )+ prompt_text = serializers.CharField(max_length=MAX_PROMPT_TEXT_CHARS, help_text=_PROMPT_TEXT_HELP)+ model = serializers.CharField(max_length=128, help_text=_MODEL_HELP)+ input_fields = serializers.ListField(+ child=serializers.CharField(), required=False, default=list, help_text=_INPUT_FIELDS_HELP+ )+ output_fields = OutputFieldSerializer(many=True, allow_empty=False, help_text=_OUTPUT_FIELDS_HELP)++ def validate_version(self, value: str) -> str:+ # The /run/ endpoint stamps every unsaved draft with exactly this string (see+ # DRAFT_VERSION_SENTINEL's docstring); accepting it here would let a saved row collide in+ # meaning with an in-flight test run's draft.+ if value == DRAFT_VERSION_SENTINEL:+ raise serializers.ValidationError(+ f"{DRAFT_VERSION_SENTINEL!r} is reserved for unsaved test runs and cannot be saved as a version."+ )+ return value++ def validate_output_fields(self, value: list[dict[str, str]]) -> list[dict[str, str]]:+ return _validate_output_fields_list(value)++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ _validate_config_shape(attrs)+ return attrs+++class RunRequestSerializer(serializers.Serializer):+ label = serializers.CharField( # type: ignore[assignment]+ max_length=128,+ help_text="Label this draft config computes, e.g. ai_pilled. Need not already exist - run classifies "+ "against an in-memory config only and persists nothing.",+ )+ prompt_text = serializers.CharField(max_length=MAX_PROMPT_TEXT_CHARS, help_text=_PROMPT_TEXT_HELP)+ model = serializers.CharField(max_length=128, help_text=_MODEL_HELP)+ input_fields = serializers.ListField(+ child=serializers.CharField(), required=False, default=list, help_text=_INPUT_FIELDS_HELP+ )+ output_fields = OutputFieldSerializer(many=True, allow_empty=False, help_text=_OUTPUT_FIELDS_HELP)+ sample = serializers.IntegerField(+ required=False,+ default=DEFAULT_SAMPLE_SIZE,+ min_value=1,+ max_value=MAX_SAMPLE_SIZE,+ help_text=f"Number of the most recently archived, distinct orgs to classify (1-{MAX_SAMPLE_SIZE}). Each "+ "sampled org costs one LLM call, so keep this bounded during iteration.",+ )++ def validate_output_fields(self, value: list[dict[str, str]]) -> list[dict[str, str]]:+ return _validate_output_fields_list(value)++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ # capture_path: this endpoint spends real LLM money the moment it starts streaming, so a+ # draft config that would fail is worth tracking even though it never reaches the LLM.+ _validate_config_shape(attrs, capture_path="ai_enrichment.run")+ return attrsdiff --git a/products/growth/backend/api/test_ai_enrichment.py b/products/growth/backend/api/test_ai_enrichment.pynew file mode 100644index 000000000000..61b2d24cc07e--- /dev/null+++ b/products/growth/backend/api/test_ai_enrichment.py@@ -0,0 +1,829 @@+import json+import uuid+import asyncio+from typing import Any++from posthog.test.base import APIBaseTest, NonAtomicAPIBaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.models.organization import Organization++from products.growth.backend.api.ai_enrichment_serializers import (+ OutputFieldSerializer,+ RunRequestSerializer,+ SaveRequestSerializer,+)+from products.growth.backend.enrichment import lab as lab_module+from products.growth.backend.enrichment.labels import (+ MAX_OUTPUT_FIELD_DESCRIPTION_CHARS,+ MAX_OUTPUT_FIELDS,+ MAX_PROMPT_TEXT_CHARS,+)+from products.growth.backend.models import EnrichmentLabelResult, EnrichmentPromptConfig, OrganizationEnrichmentFetch++# Deliberately unlike any label name used below: output keys come from output_fields, never+# from the label, and a fixture that reuses the label name would hide a regression to that.+_OUTPUT_FIELDS = [+ {"key": "is_ai", "type": "boolean", "description": ""},+ {"key": "confidence", "type": "number", "description": ""},+ {"key": "reasoning", "type": "string", "description": ""},+]+++def _mock_llm_client(+ verdict: bool = True, confidence: float = 0.9, reasoning: str = "builds ai software", verdict_key: str = "is_ai"+) -> MagicMock:+ client = MagicMock()+ # The run action chains .with_options(max_retries=0) onto get_llm_client(...); without this,+ # that call returns a fresh, unconfigured child mock and every assertion below silently+ # checks the wrong object (see enrichment_label_batch.py for the same pattern).+ client.with_options.return_value = client+ response = MagicMock()+ response.choices[0].message.content = json.dumps(+ {verdict_key: verdict, "confidence": confidence, "reasoning": reasoning}+ )+ client.chat.completions.create.return_value = response+ return client+++async def _drain(agen) -> bytes:+ return b"".join([chunk async for chunk in agen])+++def _drain_ndjson(streaming_content) -> list[dict]:+ raw = asyncio.run(_drain(streaming_content))+ return [json.loads(line) for line in raw.decode().splitlines() if line]+++class TestAIEnrichmentAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ # A prior test's successful gateway call would otherwise leak a cached model list into+ # this test (list_gateway_models is module-level state, see enrichment/lab.py).+ lab_module._model_list_cache.update({"models": None, "expires_at": 0.0})++ def _config(+ self,+ label: str = "test_label",+ version: str = "test-v1",+ is_active: bool = True,+ created_by=None,+ output_fields: list[dict[str, str]] | None = None,+ ) -> EnrichmentPromptConfig:+ return EnrichmentPromptConfig.objects.create(+ name=label,+ version=version,+ prompt_text="judge it. Email: {email}",+ output_fields=_OUTPUT_FIELDS if output_fields is None else output_fields,+ model="gpt-5-mini",+ input_fields=["name"],+ is_active=is_active,+ created_by=self.user if created_by is None else created_by,+ )++ @parameterized.expand(+ [+ ("labels", "get", "/api/growth_ai_enrichment/labels/"),+ ("models", "get", "/api/growth_ai_enrichment/models/"),+ ("configs", "get", "/api/growth_ai_enrichment/configs/?label=test_label"),+ ("save", "post", "/api/growth_ai_enrichment/save/"),+ ("run", "post", "/api/growth_ai_enrichment/run/"),+ ("activate", "post", "/api/growth_ai_enrichment/activate/"),+ ]+ )+ def test_non_staff_user_gets_403(self, _name, method, url):+ # The defining security behavior: this whole API is gated by IsStaffUser, not by any+ # personal-API-key scope, since it's registered scope_object = "INTERNAL".+ self.user.is_staff = False+ self.user.save()++ response = getattr(self.client, method)(url, {}, format="json")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_labels_lists_distinct_labels_with_version_counts_and_active_version(self):+ self._config(label="test_label", version="v1", is_active=False)+ self._config(label="test_label", version="v2", is_active=True)+ self._config(label="other_test_label", version="v1", is_active=True)++ response = self.client.get("/api/growth_ai_enrichment/labels/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ by_label = {row["label"]: row for row in response.json()["results"]}+ self.assertEqual(by_label["test_label"]["version_count"], 2)+ self.assertEqual(by_label["test_label"]["active_version"], "v2")+ self.assertEqual(by_label["other_test_label"]["version_count"], 1)+ self.assertEqual(by_label["other_test_label"]["active_version"], "v1")++ def test_configs_lists_versions_for_label_with_has_results_and_created_by(self):+ with_results = self._config(label="test_label", version="test-v1", is_active=False)+ self._config(label="test_label", version="test-v2", is_active=True)+ fetch = OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"name": "Acme"}+ )+ EnrichmentLabelResult.objects.create(+ organization=self.organization,+ fetch=fetch,+ label_name="test_label",+ prompt_version=with_results.version,+ prompt_hash=with_results.content_hash,+ model=with_results.model,+ output={"test_label": True, "confidence": 0.9, "reasoning": "x"},+ )++ response = self.client.get("/api/growth_ai_enrichment/configs/?label=test_label")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ by_version = {row["version"]: row for row in response.json()["results"]}+ self.assertEqual(set(by_version), {"test-v1", "test-v2"})+ self.assertTrue(by_version["test-v1"]["has_results"])+ self.assertFalse(by_version["test-v2"]["has_results"])+ self.assertTrue(by_version["test-v2"]["is_active"])+ self.assertEqual(by_version["test-v1"]["created_by_email"], self.user.email)++ def test_activate_flips_active_flag_and_deactivates_previous(self):+ old_active = self._config(label="test_label", version="test-v1", is_active=True)+ target = self._config(label="test_label", version="test-v2", is_active=False)++ response = self.client.post("/api/growth_ai_enrichment/activate/", {"config_id": str(target.id)}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["is_active"])+ target.refresh_from_db()+ old_active.refresh_from_db()+ self.assertTrue(target.is_active)+ self.assertFalse(old_active.is_active)++ def test_activate_reads_the_label_under_the_row_lock_not_before_it(self):+ # Reading config.name before the transaction meant a rename landing in between aimed the+ # deactivation at the retired name, matched no siblings, and left two rows active under+ # the new one - which growth_prompt_config_one_active rejects as an unhandled 500.+ old_active = self._config(label="old_label", version="v1", is_active=True)+ target = self._config(label="old_label", version="v2", is_active=False)+ EnrichmentPromptConfig.objects.filter(name="old_label").update(name="new_label")++ response = self.client.post("/api/growth_ai_enrichment/activate/", {"config_id": str(target.id)}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ target.refresh_from_db()+ old_active.refresh_from_db()+ self.assertTrue(target.is_active)+ self.assertFalse(old_active.is_active)++ def test_activate_unknown_config_returns_404(self):+ response = self.client.post(+ "/api/growth_ai_enrichment/activate/", {"config_id": str(uuid.uuid4())}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_models_returns_gateway_list_when_client_works(self):+ fake_client = MagicMock()+ fake_client.models.list.return_value = [MagicMock(id="gpt-5.2"), MagicMock(id="claude-fable-5")]++ with patch("products.growth.backend.enrichment.lab.get_llm_client", return_value=fake_client):+ response = self.client.get("/api/growth_ai_enrichment/models/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ ids = {row["id"] for row in response.json()["results"]}+ self.assertEqual(ids, {"gpt-5.2", "claude-fable-5"})++ def test_models_returns_empty_rather_than_a_stale_list_when_the_gateway_is_down(self):+ with patch("products.growth.backend.enrichment.lab.get_llm_client", side_effect=RuntimeError("gateway down")):+ response = self.client.get("/api/growth_ai_enrichment/models/")++ # No curated mirror: a hand-maintained fallback goes stale silently.+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"], [])++ def test_save_creates_exactly_the_submitted_bytes(self):+ payload = {+ "label": "new_label",+ "prompt_text": "a brand new experimental prompt. Email: {email}",+ "model": "gpt-5-nano",+ "input_fields": ["name", "description"],+ "output_fields": _OUTPUT_FIELDS,+ }++ response = self.client.post("/api/growth_ai_enrichment/save/", payload, format="json")++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ config = EnrichmentPromptConfig.objects.get(name="new_label")+ self.assertEqual(config.prompt_text, payload["prompt_text"])+ self.assertEqual(config.model, payload["model"])+ self.assertEqual(config.input_fields, payload["input_fields"])+ self.assertEqual(config.output_fields, payload["output_fields"])+ self.assertFalse(config.is_active)+ self.assertEqual(config.created_by, self.user)+ self.assertEqual(response.json()["id"], str(config.id))++ def test_save_assigns_the_suggested_version_when_none_supplied(self):+ payload = {+ "label": "seq_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": _OUTPUT_FIELDS,+ }++ first = self.client.post("/api/growth_ai_enrichment/save/", payload, format="json")+ second = self.client.post("/api/growth_ai_enrichment/save/", payload, format="json")++ self.assertEqual(first.status_code, status.HTTP_201_CREATED)+ self.assertEqual(second.status_code, status.HTTP_201_CREATED)+ self.assertEqual([first.json()["version"], second.json()["version"]], ["v1", "v2"])++ def test_save_never_reuses_a_retired_version_string(self):+ # Counting rows instead of reading the highest suffix would hand out v2 again here, and+ # every verdict already stamped v2 would then read as this new prompt's output.+ self._config(label="seq_label", version="v1", is_active=False)+ self._config(label="seq_label", version="v2", is_active=False)+ EnrichmentPromptConfig.objects.filter(name="seq_label", version="v1").delete()++ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {"label": "seq_label", "prompt_text": "x", "model": "gpt-5-mini", "output_fields": _OUTPUT_FIELDS},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["version"], "v3")++ def test_save_suggests_the_next_version_from_a_v_suffix_anywhere_in_a_legacy_name(self):+ # "ai-pilled-clay-v1" doesn't fullmatch v<n>, but it still means v1 was taken - suggesting+ # v1 again here would let the new row collide in spirit (if not in DB uniqueness) with an+ # already-shipped classifier version.+ self._config(label="legacy_label", version="ai-pilled-clay-v1", is_active=True)++ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {"label": "legacy_label", "prompt_text": "x", "model": "gpt-5-mini", "output_fields": _OUTPUT_FIELDS},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["version"], "v2")++ def test_save_falls_back_to_the_row_count_when_no_version_has_a_v_suffix_at_all(self):+ self._config(label="odd_label", version="alpha", is_active=True)+ self._config(label="odd_label", version="beta", is_active=False)++ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {"label": "odd_label", "prompt_text": "x", "model": "gpt-5-mini", "output_fields": _OUTPUT_FIELDS},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["version"], "v3")++ def test_save_rejects_the_run_endpoints_draft_sentinel_as_a_version(self):+ # RunRequestSerializer stamps every unsaved test-run draft "lab-draft"; accepting it here+ # would let a real saved row collide in meaning with an in-flight, unpersisted test run.+ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {+ "label": "sentinel_label",+ "version": "lab-draft",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": _OUTPUT_FIELDS,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(EnrichmentPromptConfig.objects.filter(name="sentinel_label").count(), 0)++ def test_save_accepts_a_caller_supplied_version(self):+ payload = {+ "label": "manual_version_label",+ "version": "hand-picked-v1",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": _OUTPUT_FIELDS,+ }++ response = self.client.post("/api/growth_ai_enrichment/save/", payload, format="json")++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["version"], "hand-picked-v1")++ def test_save_rejects_a_version_that_collides_with_an_existing_one(self):+ # (name, version) must be unique - and this is the API's only surface for creating a+ # version, so a 500 here would be a real request path, not an edge case.+ self._config(label="collide_label", version="v1", is_active=False)++ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {+ "label": "collide_label",+ "version": "v1",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": _OUTPUT_FIELDS,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(EnrichmentPromptConfig.objects.filter(name="collide_label").count(), 1)++ @parameterized.expand(+ [+ ("bad_key", [{"key": "Bad-Key", "type": "boolean", "description": ""}]),+ ("bad_type", [{"key": "ok_key", "type": "float", "description": ""}]),+ ("duplicate_key", [{"key": "a", "type": "boolean"}, {"key": "a", "type": "number"}]),+ ("reserved_key", [{"key": "meta", "type": "boolean"}]),+ # output_fields is the whole output contract, so an empty one is a config that+ # asks the model for nothing and stores nothing.+ ("empty", []),+ ("too_many_fields", [{"key": f"f{i}", "type": "boolean"} for i in range(MAX_OUTPUT_FIELDS + 1)]),+ (+ "description_too_long",+ [{"key": "flag", "type": "boolean", "description": "x" * (MAX_OUTPUT_FIELD_DESCRIPTION_CHARS + 1)}],+ ),+ ]+ )+ def test_save_rejects_invalid_output_fields_schema(self, _name, output_fields):+ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {+ "label": "schema_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": output_fields,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(EnrichmentPromptConfig.objects.filter(name="schema_label").count(), 0)++ def test_save_rejects_input_fields_over_the_column_limit(self):+ # validate_input_fields (enrichment/labels.py), reused rather than reimplemented: more+ # input_fields than bound_inputs will carry means the tail is silently dropped from both+ # the prompt and the stored record on every future run of this version.+ response = self.client.post(+ "/api/growth_ai_enrichment/save/",+ {+ "label": "too_many_fields_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": [f"field_{i}" for i in range(41)],+ "output_fields": _OUTPUT_FIELDS,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(EnrichmentPromptConfig.objects.filter(name="too_many_fields_label").count(), 0)++ def test_save_has_no_mutation_endpoint_for_an_existing_version(self):+ # Versions are immutable: the freeze is enforced by this viewset simply never defining+ # update/partial_update/destroy, not by any runtime check, so there is no detail route+ # at all to send a mutation to.+ config = self._config(label="frozen_label", version="v1")++ for method in ("put", "patch", "delete"):+ response = getattr(self.client, method)(+ f"/api/growth_ai_enrichment/{config.id}/", {"prompt_text": "changed"}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, method)+ config.refresh_from_db()+ self.assertEqual(config.prompt_text, "judge it. Email: {email}")++ def test_run_rechecks_consent_immediately_before_classification_and_skips_a_mid_run_revocation(self):+ # The sample is consent-filtered once, up front, at prefetch (_build_run_inputs) - but a+ # run streams over seconds to minutes, long enough for an admin to revoke consent after+ # that filter already ran. This organization passes the prefetch filter (consent approved+ # by default in APIBaseTest), so only classify_fetch_for_run's own recheck can catch it.+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"name": "Acme"}+ )+ client = _mock_llm_client()++ with (+ patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=client),+ patch("products.growth.backend.enrichment.lab.ai_processing_approved", return_value=False),+ ):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "mid_run_revoke_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ verdict_rows = [row for row in rows if "summary" not in row]+ client.chat.completions.create.assert_not_called()+ self.assertTrue(verdict_rows[0]["meta"]["skipped"])++ @parameterized.expand(+ [+ ("too_many_fields", [{"key": f"f{i}", "type": "boolean"} for i in range(MAX_OUTPUT_FIELDS + 1)]),+ (+ "description_too_long",+ [{"key": "flag", "type": "boolean", "description": "x" * (MAX_OUTPUT_FIELD_DESCRIPTION_CHARS + 1)}],+ ),+ ]+ )+ def test_run_rejects_output_fields_over_the_caps(self, _name, output_fields):+ # Wiring guard for RunRequestSerializer: the boundary logic itself is proven in+ # TestSaveAndRunSerializerCaps without a request round trip, this only confirms the+ # viewset still surfaces that as a 400 on this endpoint too, same as /save/ above.+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "run_cap_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": output_fields,+ "sample": 1,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_run_rejects_sample_over_the_max(self):+ # This endpoint spends real LLM money per sampled org - the max (10) must be enforced+ # before any candidates are fetched or any LLM client is built.+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "test_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "output_fields": _OUTPUT_FIELDS,+ "sample": 11,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "sample")++ def test_run_rejects_an_invalid_draft_config_with_400_not_500(self):+ # A config error (too many input_fields for bound_inputs to carry) must surface as a+ # normal 400 raised before streaming starts, not an unhandled 500 - and definitely not a+ # 200 stream that only reveals the problem mid-flight.+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "bad_config_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": [f"field_{i}" for i in range(41)],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_run_constructs_its_client_with_max_retries_zero(self):+ # tenacity already owns retries inside classify_payload; the SDK's own retries stacking+ # on top would multiply spend on every 429 tenacity is already backing off from.+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"name": "Acme"}+ )+ client = _mock_llm_client()++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=client) as get_client:+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "test_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )+ _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]++ get_client.assert_called_once_with(product="growth")+ client.with_options.assert_called_once_with(max_retries=0)++ def test_run_is_throttled_for_session_auth(self):+ # The global throttles are PersonalApiKeyRateThrottle subclasses, a structural no-op for+ # session-authenticated requests with no personal API key - this endpoint needs its own,+ # since each allowed call can cost several real LLM completions.+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"name": "Acme"}+ )+ payload = {+ "label": "throttle_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ }++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=_mock_llm_client()):+ statuses = []+ for _ in range(11):+ response = self.client.post("/api/growth_ai_enrichment/run/", payload, format="json")+ if response.status_code == status.HTTP_200_OK:+ _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ statuses.append(response.status_code)++ self.assertEqual(statuses.count(status.HTTP_200_OK), 10)+ self.assertEqual(statuses[-1], status.HTTP_429_TOO_MANY_REQUESTS)+++class TestAIEnrichmentRunClassification(NonAtomicAPIBaseTest):+ """/run/ hands each sampled fetch to a real ThreadPoolExecutor worker (classify_fetch_for_run,+ enrichment/lab.py), which opens its own DB connection to recheck consent. Under plain+ APIBaseTest (TestCase), that worker connection cannot see this test's own DB writes - they+ sit in TestCase's outer, never-committed transaction, invisible to any other connection - so+ a fresh query from the worker thread finds no such organization at all and the consent+ recheck false-negatives on every row. NonAtomicAPIBaseTest (TransactionTestCase) commits for+ real instead. Tests here are the ones whose assertions depend on classify_fetch_for_run+ actually reaching classify_payload; pure-validation and pre-streaming /run/ tests stay on the+ faster TestAIEnrichmentAPI above.++ CLASS_DATA_LEVEL_SETUP = False: TransactionTestCase flushes every table between tests (see+ _fixture_teardown), including the org/team/user setUpTestData creates - fixtures made once in+ setUpClass would only exist for this class's first test. Per-test setup recreates them fresh+ each time instead.+ """++ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ lab_module._model_list_cache.update({"models": None, "expires_at": 0.0})++ def test_run_streams_ndjson_verdicts_for_an_unsaved_draft_and_persists_nothing(self):+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization,+ provider="harmonic",+ payload={"name": "Acme", "contactEmail": "[email protected]"},+ )++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=_mock_llm_client()):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "unsaved_label",+ "prompt_text": "a draft prompt. Email: {email}",+ "model": "gpt-5-mini",+ "input_fields": ["name", "contactEmail"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 5,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ verdict_rows = [row for row in rows if "summary" not in row]+ (summary_row,) = [row for row in rows if "summary" in row]++ self.assertEqual(len(verdict_rows), 1)+ self.assertEqual(verdict_rows[0]["company"], "Acme")+ self.assertEqual(+ verdict_rows[0]["outputs"], {"is_ai": True, "confidence": 0.9, "reasoning": "builds ai software"}+ )+ # Only the domain reaches the prompt/stored record - to_domain/bound_inputs (labels.py)+ # must not be bypassed by this endpoint's own request-shape handling.+ self.assertEqual(verdict_rows[0]["inputs"], {"name": "Acme", "contactEmail": "example.com"})+ self.assertEqual(summary_row["summary"], {"classified": 1, "unknown": 0, "errors": 0})+ # "unsaved_label" must never touch the DB - run classifies an in-memory config only.+ self.assertEqual(EnrichmentPromptConfig.objects.filter(name="unsaved_label").count(), 0)+ self.assertEqual(EnrichmentLabelResult.objects.count(), 0)++ def test_run_reports_no_inputs_for_a_not_found_archived_payload(self):+ # classify_payload short-circuits on the miss sentinel before ever extracting a field -+ # a row for one must not display inputs the classifier never touched, even though "name"+ # is present in the raw payload and configured as an input field.+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization,+ provider="harmonic",+ payload={"companyFound": False, "name": "Acme"},+ )++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=_mock_llm_client()):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "miss_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )++ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ verdict_rows = [row for row in rows if "summary" not in row]+ self.assertEqual(verdict_rows[0]["inputs"], {})++ def test_run_reports_meta_skipped_for_a_skipped_row(self):+ # The frontend prefers meta.skipped over sniffing individual values for the literal+ # "unknown" string - this is the wire contract it depends on.+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"companyFound": False}+ )++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=_mock_llm_client()):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "skip_meta_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )++ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ verdict_rows = [row for row in rows if "summary" not in row]+ self.assertTrue(verdict_rows[0]["meta"]["skipped"])+ self.assertEqual(verdict_rows[0]["outputs"]["is_ai"], "unknown")++ @parameterized.expand([("declined", False), ("unset", None)])+ def test_run_excludes_orgs_without_ai_processing_consent(self, _name, consent_value):+ # Matches the gate the batch runner and dry-run command apply per row+ # (ai_processing_approved) - a lab test run must not be a side door that sends an+ # unconsented org's data to the LLM just because it's a smaller sample.+ consented_org = self.organization+ OrganizationEnrichmentFetch.objects.create(+ organization=consented_org, provider="harmonic", payload={"name": "Acme"}+ )+ declined_org = Organization.objects.create(name="Declined Co", is_ai_data_processing_approved=consent_value)+ OrganizationEnrichmentFetch.objects.create(+ organization=declined_org, provider="harmonic", payload={"name": "Declined Co"}+ )+ client = _mock_llm_client()++ with patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=client):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "consent_check_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 10,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]+ companies = {row["company"] for row in rows if "summary" not in row}+ self.assertEqual(companies, {"Acme"})+ # Not just absent from the output - the declined org's payload must never have reached+ # the client at all.+ sent_payloads = [+ call.kwargs["messages"][1]["content"] for call in client.chat.completions.create.call_args_list+ ]+ self.assertTrue(all("Declined Co" not in payload for payload in sent_payloads))++ def test_run_captures_and_reports_a_per_row_failure_without_500ing_the_whole_stream(self):+ OrganizationEnrichmentFetch.objects.create(+ organization=self.organization, provider="harmonic", payload={"name": "Acme"}+ )+ failing_client = MagicMock()+ failing_client.with_options.return_value = failing_client+ failing_client.chat.completions.create.side_effect = RuntimeError("gateway timeout")++ # The patch must still be active while the stream is drained, not just during the POST:+ # classify_fetch_for_run runs in a thread-pool worker that only executes (and only then+ # calls capture_exception) once something actually iterates streaming_content.+ with (+ patch("products.growth.backend.api.ai_enrichment.get_llm_client", return_value=failing_client),+ patch("products.growth.backend.enrichment.lab.capture_exception") as mock_capture,+ patch("tenacity.nap.time.sleep"),+ ):+ response = self.client.post(+ "/api/growth_ai_enrichment/run/",+ {+ "label": "flaky_label",+ "prompt_text": "x",+ "model": "gpt-5-mini",+ "input_fields": ["name"],+ "output_fields": _OUTPUT_FIELDS,+ "sample": 1,+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ rows = _drain_ndjson(response.streaming_content) # type: ignore[attr-defined]++ verdict_rows = [row for row in rows if "summary" not in row]+ (summary_row,) = [row for row in rows if "summary" in row]+ self.assertIsNone(verdict_rows[0]["outputs"])+ self.assertIn("RuntimeError", verdict_rows[0]["error"])+ # Extraction happens before the LLM call, so a row that fails it still reports what would+ # have been sent - an empty "inputs sent" here would be a lie about what was attempted.+ self.assertEqual(verdict_rows[0]["inputs"], {"name": "Acme"})+ self.assertEqual(summary_row["summary"], {"classified": 0, "unknown": 0, "errors": 1})+ mock_capture.assert_called_once()+++class TestRunError(SimpleTestCase):+ """No DB needed: _run_error is pure string formatting plus a capture_exception call."""++ def test_does_not_truncate_the_error_message_at_the_old_120_char_cap(self):+ long_message = "x" * 500+ config = EnrichmentPromptConfig(name="test_label", model="gpt-5-mini")++ with patch("products.growth.backend.enrichment.lab.capture_exception"):+ formatted = lab_module._run_error(config, RuntimeError(long_message), "test")++ self.assertIn(long_message, formatted)+++class TestSaveAndRunSerializerCaps(SimpleTestCase):+ """Field-level max_length/count caps run inside is_valid()'s to_internal_value phase, before+ the object-level validate() that needs a request context - no DB needed. The /save/ and+ /run/ 400 tests above are the wiring guard that each viewset still calls is_valid() at all;+ these are the boundary tests themselves, run once per request serializer since+ SaveRequestSerializer and RunRequestSerializer each declare prompt_text's max_length and+ output_fields independently, even though both delegate to the same shared helpers."""++ def _valid_payload(self, **overrides: Any) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "label": "cap_test_label",+ "prompt_text": "judge it.",+ "model": "gpt-5-mini",+ "output_fields": [{"key": "flag", "type": "boolean", "description": ""}],+ }+ payload.update(overrides)+ return payload++ @parameterized.expand([("save", SaveRequestSerializer), ("run", RunRequestSerializer)])+ def test_prompt_text_over_the_char_cap_is_rejected(self, _name, serializer_class):+ serializer = serializer_class(data=self._valid_payload(prompt_text="x" * (MAX_PROMPT_TEXT_CHARS + 1)))++ self.assertFalse(serializer.is_valid())+ self.assertEqual(serializer.errors["prompt_text"][0].code, "max_length")++ @parameterized.expand([("save", SaveRequestSerializer), ("run", RunRequestSerializer)])+ def test_prompt_text_at_the_char_cap_is_accepted(self, _name, serializer_class):+ serializer = serializer_class(data=self._valid_payload(prompt_text="x" * MAX_PROMPT_TEXT_CHARS))++ self.assertTrue(serializer.is_valid(), serializer.errors)++ @parameterized.expand([("save", SaveRequestSerializer), ("run", RunRequestSerializer)])+ def test_output_fields_over_the_count_cap_is_rejected(self, _name, serializer_class):+ too_many = [{"key": f"field_{i}", "type": "boolean", "description": ""} for i in range(MAX_OUTPUT_FIELDS + 1)]+ serializer = serializer_class(data=self._valid_payload(output_fields=too_many))++ self.assertFalse(serializer.is_valid())+ self.assertIn(f"At most {MAX_OUTPUT_FIELDS}", str(serializer.errors["output_fields"]))++ @parameterized.expand([("save", SaveRequestSerializer), ("run", RunRequestSerializer)])+ def test_output_fields_at_the_count_cap_is_accepted(self, _name, serializer_class):+ exactly_max = [{"key": f"field_{i}", "type": "boolean", "description": ""} for i in range(MAX_OUTPUT_FIELDS)]+ serializer = serializer_class(data=self._valid_payload(output_fields=exactly_max))++ self.assertTrue(serializer.is_valid(), serializer.errors)++ def test_output_field_description_over_the_char_cap_is_rejected(self):+ serializer = OutputFieldSerializer(+ data={"key": "flag", "type": "boolean", "description": "x" * (MAX_OUTPUT_FIELD_DESCRIPTION_CHARS + 1)}+ )++ self.assertFalse(serializer.is_valid())+ self.assertEqual(serializer.errors["description"][0].code, "max_length")++ def test_output_field_description_at_the_char_cap_is_accepted(self):+ serializer = OutputFieldSerializer(+ data={"key": "flag", "type": "boolean", "description": "x" * MAX_OUTPUT_FIELD_DESCRIPTION_CHARS}+ )++ self.assertTrue(serializer.is_valid(), serializer.errors)++ @parameterized.expand([("save", SaveRequestSerializer), ("run", RunRequestSerializer)])+ def test_output_field_description_cap_propagates_through_the_nested_list(self, _name, serializer_class):+ # OutputFieldSerializer is nested (many=True) under both request serializers - this+ # confirms the cap actually reaches a caller through that nesting, not just when+ # OutputFieldSerializer is exercised standalone above.+ too_long = [{"key": "flag", "type": "boolean", "description": "x" * (MAX_OUTPUT_FIELD_DESCRIPTION_CHARS + 1)}]+ serializer = serializer_class(data=self._valid_payload(output_fields=too_long))++ self.assertFalse(serializer.is_valid())+ self.assertIn("description", serializer.errors["output_fields"][0])diff --git a/products/growth/backend/enrichment/lab.py b/products/growth/backend/enrichment/lab.pynew file mode 100644index 000000000000..85e28bc5d73d--- /dev/null+++ b/products/growth/backend/enrichment/lab.py@@ -0,0 +1,173 @@+"""Runner pieces behind the staff AI enrichment lab endpoints (products/growth/backend/api/ai_enrichment.py):+the gateway model list, and the concurrent stream that drives a test run.++Org-agnostic on purpose: everything here takes (config, fetch, client) in and a verdict out.+Callers build the input fetches themselves - see products.growth.backend.enrichment.labels for+recent_latest_fetches_qs / signup_domain_for_organization, the internal fetch source.+"""++import time+import asyncio+from collections.abc import AsyncIterator+from concurrent.futures import ThreadPoolExecutor+from typing import Any++from django.db import close_old_connections, connection++import structlog+from openai import OpenAI++from posthog.exceptions_capture import capture_exception+from posthog.llm.gateway_client import get_llm_client++from products.growth.backend.enrichment.labels import (+ ai_processing_approved,+ bound_inputs,+ classify_payload,+ extract_input_fields,+ unknown_output,+)+from products.growth.backend.models import EnrichmentPromptConfig, OrganizationEnrichmentFetch++logger = structlog.get_logger(__name__)++# Bounded so a test run (the staff API's /run/) stays a short request, not a batch job - and+# caps real LLM spend per call.+DEFAULT_SAMPLE_SIZE = 5+MAX_SAMPLE_SIZE = 10+DEFAULT_WORKERS = 5++# The version stamped on the in-memory, unsaved config a /run/ test-run classifies against - never+# persisted, so it never collides with a real saved version string. Also rejected as a+# caller-supplied version on /save/ (ai_enrichment_serializers.py), so a client can't accidentally+# freeze a row that then reads as an in-flight draft.+DRAFT_VERSION_SENTINEL = "lab-draft"++_MODEL_LIST_CACHE_SECONDS = 300+# Module-level so a cold cache (first call, or one past its TTL) is shared across requests+# instead of re-fetched per request. Reset in tests via `_model_list_cache["models"] = None`.+_model_list_cache: dict[str, Any] = {"models": None, "expires_at": 0.0}+++def list_gateway_models() -> list[str]:+ """Live gateway model ids (client.models.list()), cached for _MODEL_LIST_CACHE_SECONDS.++ Returns an empty list on ANY exception rather than falling back to a curated copy. The+ gateway is the source of truth, and a hand-maintained mirror goes stale silently: it keeps+ offering models the gateway has dropped and hides ones it has added, with no signal either+ way. Same reasoning as products/slack_app/backend/services/llm_models.py. An empty result is+ never cached, so the next call retries immediately.+ """+ now = time.monotonic()+ if _model_list_cache["models"] is not None and now < _model_list_cache["expires_at"]:+ return list(_model_list_cache["models"])+ try:+ client = get_llm_client(product="growth")+ models = sorted({model.id for model in client.models.list()})+ if not models:+ raise ValueError("gateway returned no models")+ except Exception as e:+ # This failure empties the model picker with no other symptom, so it has to reach error+ # tracking rather than only a log line nobody reads.+ capture_exception(e, {"path": "list_gateway_models"})+ return []+ _model_list_cache["models"] = models+ _model_list_cache["expires_at"] = now + _MODEL_LIST_CACHE_SECONDS+ return list(models)+++# (company, domain, output-or-None, error-or-None, inputs-sent) for one classified item - the+# staff API's /run/ stream shape (api/ai_enrichment.py). `inputs` is populated on both the success+# and the error path (see classify_fetch_for_run) - a row that failed the LLM call still shows+# what would have been sent, since extraction happens before that call either way.+RunClassifyResult = tuple[str, str | None, dict[str, Any] | None, str | None, dict[str, Any]]+++def _run_error(config: EnrichmentPromptConfig, e: Exception, path: str) -> str:+ """Report the failure, and render it for the results table led by the exception type: an+ OpenAI SDK error's str() can carry the gateway URL and upstream response bodies. The 2000-char+ cap is ours, not upstream's - generous enough that the frontend's error-tooltip rarely+ truncates mid-sentence, while still bounded against a pathological upstream error body."""+ capture_exception(e, {"label": config.name, "model": config.model, "path": path})+ return f"{type(e).__name__}: {str(e)[:2000]}"+++def classify_fetch_for_run(+ config: EnrichmentPromptConfig, pair: tuple[OrganizationEnrichmentFetch, str | None], client: OpenAI+) -> RunClassifyResult:+ fetch, signup_domain = pair+ company = fetch.payload.get("name") or fetch.organization.name+ # Computed up front, independent of the try/except below: classify_payload only returns this+ # (nested in output["inputs"]) on success, and re-deriving it here - cheap, pure extraction,+ # no LLM call - is simpler than threading a partial result out of a caught exception. Without+ # it, a row that fails the LLM call would show an empty "inputs sent" despite having built one.+ # Mirrors classify_payload's own short-circuit for a missing/not-found archived payload+ # (`{"companyFound": False}`, or no payload at all): it never extracts from one, so a row for+ # one must not display inputs the classifier never touched.+ if not fetch.payload or fetch.payload.get("companyFound") is False:+ inputs: dict[str, Any] = {}+ else:+ inputs = bound_inputs(extract_input_fields(fetch.payload, config.input_fields))+ try:+ # Thread-local DB connection: drop any stale one left by this pool thread's previous+ # iteration before the consent recheck query below - same pattern as+ # enrichment_label_batch.py's threaded worker. Closed again in `finally` so it isn't held+ # open past this iteration, into this worker thread's next one.+ close_old_connections()+ # Re-checked here, not just at the prefetch filter in _build_run_inputs: a run streams+ # over several seconds to minutes, long enough for an admin to revoke consent mid-run. A+ # stale approval read before streaming started must not still reach the LLM.+ if not ai_processing_approved(fetch.organization_id):+ output = unknown_output(config, signup_domain, "AI processing consent was revoked mid-run")+ return company, signup_domain, output, None, {}+ output = classify_payload(config, fetch.payload, signup_domain, client)+ except Exception as e:+ return company, signup_domain, None, _run_error(config, e, "classify_fetch_for_run"), inputs+ finally:+ connection.close()+ return company, signup_domain, output, None, inputs+++async def stream_run_classifications(+ config: EnrichmentPromptConfig,+ items: list[tuple[OrganizationEnrichmentFetch, str | None]],+ client: OpenAI,+ workers: int = DEFAULT_WORKERS,+) -> AsyncIterator[RunClassifyResult]:+ """Classify each archived fetch concurrently, yielding one result as each completes.++ Async generator on purpose: under ASGI, Django fully buffers a sync iterator before sending+ anything, which silently defeats streaming."""+ loop = asyncio.get_running_loop()+ pool = ThreadPoolExecutor(max_workers=workers)+ try:+ tasks = [loop.run_in_executor(pool, classify_fetch_for_run, config, item, client) for item in items]+ for task in asyncio.as_completed(tasks):+ yield await task+ finally:+ # cancel_futures so a client disconnect stops paying for calls that haven't started yet.+ pool.shutdown(wait=False, cancel_futures=True)+++def format_run_row(+ config: EnrichmentPromptConfig,+ company: str,+ domain: str | None,+ output: dict[str, Any] | None,+ error: str | None,+ inputs: dict[str, Any],+) -> dict[str, Any]:+ """Build one ndjson row for the staff API's /run/ stream (api/ai_enrichment.py). Values are+ keyed by the config's output fields; the label name never appears in the data. `inputs` is+ what was actually sent to the LLM (post to_domain/bound_inputs reduction) - surfaced so a+ staff user can see why a verdict came out the way it did without re-running the query, and+ populated on an error row too (see classify_fetch_for_run). `meta` carries classify_payload's+ provenance dict verbatim (see labels.py's is_unknown_output) - the frontend prefers+ `meta.skipped` over sniffing individual values for the literal "unknown" string, since a+ schema with no boolean output field never writes that sentinel into any value at all.+ """+ if error is not None:+ return {"company": company, "domain": domain, "inputs": inputs, "outputs": None, "error": error}+ assert output is not None+ outputs = {field["key"]: output.get(field["key"]) for field in config.output_fields}+ return {"company": company, "domain": domain, "inputs": inputs, "outputs": outputs, "meta": output.get("meta", {})}diff --git a/products/growth/backend/enrichment/labels.py b/products/growth/backend/enrichment/labels.pyindex 90424e8e6877..95385967d382 100644--- a/products/growth/backend/enrichment/labels.py+++ b/products/growth/backend/enrichment/labels.py@@ -28,6 +28,9 @@ UNKNOWN: Literal["unknown"] = "unknown"# validate_output_fields rejects any configured output field that shadows one of these.RESERVED_OUTPUT_FIELD_KEYS = frozenset({"meta", "inputs"})+# Schema constraints the API validates a config's output_fields against.+OUTPUT_FIELD_KEY_RE = re.compile(r"^[a-z][a-z0-9_]*$")+_TRUE_STRINGS = frozenset({"true", "yes", "y", "1"})_FALSE_STRINGS = frozenset({"false", "no", "n", "0"})@@ -48,6 +51,14 @@ MAX_INPUT_DEPTH = 6# not a reservation, so the headroom is free.MAX_OUTPUT_TOKENS = 4000+# Bounds on the prompt config's own authored content (prompt_text, output_fields) - not the+# archived payload data above. Defined here, not in ai_enrichment_serializers.py, so any other+# consumer of EnrichmentPromptConfig content (e.g. the admin form) can share the same numbers+# instead of drifting to its own.+MAX_PROMPT_TEXT_CHARS = 20_000+MAX_OUTPUT_FIELDS = 20+MAX_OUTPUT_FIELD_DESCRIPTION_CHARS = 400+_TRUNCATED_AT_MAX_DEPTH = "…(truncated: exceeded max input nesting depth)"@@ -251,6 +262,9 @@ _OUTPUT_FIELD_COERCERS: dict[str, Callable[[Any], Any]] = {"string": _coerce_str,}+# Derived from the coercer table so the API can never accept a type this module has no coercer for.+OUTPUT_FIELD_TYPES = tuple(_OUTPUT_FIELD_COERCERS)+# Default range for these keys when a field declares no explicit min/max, so configs written# before ranges were expressible keep their old behavior._UNIT_INTERVAL_KEYS = frozenset({"confidence"})@@ -400,9 +414,13 @@ def _response_meta(response: Any) -> dict[str, Any]:return meta-def _unknown_output(config: EnrichmentPromptConfig, signup_domain: str | None, reason: str) -> dict[str, Any]:+def unknown_output(config: EnrichmentPromptConfig, signup_domain: str | None, reason: str) -> dict[str, Any]:"""Only the configured keys, same as a real call: why the run was skipped goes in meta, which- is reserved for provenance, because a schema need not have a "reasoning" key."""+ is reserved for provenance, because a schema need not have a "reasoning" key. Public: besides+ classify_payload's own short-circuits below, enrichment/lab.py's classify_fetch_for_run calls+ this directly for its own consent-revoked-mid-run short-circuit, which must never reach+ classify_payload (and therefore the LLM) in the first place.+ """output: dict[str, Any] = {}verdict_key = verdict_field_key(config)if verdict_key is not None:@@ -414,9 +432,9 @@ def _unknown_output(config: EnrichmentPromptConfig, signup_domain: str | None, rdef is_unknown_output(output: dict[str, Any]) -> bool:"""The authoritative "was this skipped" marker for accounting. verdict_field_key can be None- (a schema with no boolean field), in which case _unknown_output writes no verdict key at all -+ (a schema with no boolean field), in which case unknown_output writes no verdict key at all -so callers that count unknowns by checking a verdict key miss every skipped row under such a- schema. meta.skipped is set on every _unknown_output call regardless of schema shape."""+ schema. meta.skipped is set on every unknown_output call regardless of schema shape."""return bool(output.get("meta", {}).get("skipped"))@@ -428,14 +446,14 @@ def classify_payload(# Not-found fetches archive core.py's _MISS_PAYLOAD ({"companyFound": False}); that's# evidence of absence, not a thin signal to guess from, so skip the LLM entirely.if not payload or payload.get("companyFound") is False:- return _unknown_output(config, signup_domain, "missing or empty archived payload")+ return unknown_output(config, signup_domain, "missing or empty archived payload")# Checked after resolving, not before: a payload that's present but has none of the configured# paths would otherwise bill a call to ask the model about "Company data: {}".extracted = extract_input_fields(payload, config.input_fields)inputs = bound_inputs(extracted)if not inputs:- return _unknown_output(config, signup_domain, "archived payload has none of the configured input fields")+ return unknown_output(config, signup_domain, "archived payload has none of the configured input fields")messages = build_messages(config, inputs, signup_domain)output, meta = _call_and_parse(config, messages, client)diff --git a/products/growth/backend/routes.py b/products/growth/backend/routes.pyindex ee8124408357..d8f860e3656e 100644--- a/products/growth/backend/routes.py+++ b/products/growth/backend/routes.py@@ -1,5 +1,6 @@from posthog.api.routing import RouterRegistry+from products.growth.backend.api.ai_enrichment import AIEnrichmentViewSetfrom products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSetfrom products.growth.backend.api.product_push import ProductPushCampaignViewSet@@ -14,3 +15,5 @@ def register_routes(routers: RouterRegistry) -> None:"organization_product_push_campaign",["organization_id"],)+ # Staff-only, unscoped: prompt configs are instance-global, not team/org scoped.+ routers.root.register(r"growth_ai_enrichment", AIEnrichmentViewSet, "growth_ai_enrichment")diff --git a/products/growth/backend/tests/test_enrichment_labels_validation.py b/products/growth/backend/tests/test_enrichment_labels_validation.pyindex bba6816b229b..db6a52fa0524 100644--- a/products/growth/backend/tests/test_enrichment_labels_validation.py+++ b/products/growth/backend/tests/test_enrichment_labels_validation.py@@ -204,7 +204,7 @@ class TestIsUnknownOutput(SimpleTestCase):])def test_is_unknown_output(self, _name: str, output: dict[str, Any], expected: bool) -> None:- # A schema with no boolean output field has no verdict key for _unknown_output to write,+ # A schema with no boolean output field has no verdict key for unknown_output to write,# so counting unknowns by checking a verdict key misses every skipped row under it.assert is_unknown_output(output) is expecteddiff --git a/products/growth/frontend/aiEnrichment/AIEnrichmentResultsTable.tsx b/products/growth/frontend/aiEnrichment/AIEnrichmentResultsTable.tsxnew file mode 100644index 000000000000..7714f38fea4b--- /dev/null+++ b/products/growth/frontend/aiEnrichment/AIEnrichmentResultsTable.tsx@@ -0,0 +1,122 @@+import { useValues } from 'kea'++import { LemonBanner, LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { AIEnrichmentRunRow, aiEnrichmentLogic } from './aiEnrichmentLogic'+import {+ OutputColumnSpec,+ deriveOutputColumns,+ isSkippedRow,+ summarizeError,+ summarizeInputs,+} from './aiEnrichmentResultColumns'++function outputCell(row: AIEnrichmentRunRow, column: OutputColumnSpec): JSX.Element | string | null {+ if (row.outputs === null) {+ return <span className="text-secondary">–</span>+ }+ const value = row.outputs[column.key]+ if (value === undefined) {+ return <span className="text-secondary">–</span>+ }+ // Checked before the column's declared type: a skipped/indeterminate row can land in any+ // typed column, and a boolean column would otherwise render its sentinel as a truthy green+ // tag indistinguishable from a real positive verdict.+ if (isSkippedRow(row)) {+ return <LemonTag type="muted">unknown</LemonTag>+ }+ if (column.type === 'boolean') {+ return <LemonTag type={value ? 'success' : 'danger'}>{String(value)}</LemonTag>+ }+ if (column.type === 'number') {+ return <div className="text-right tabular-nums">{value}</div>+ }+ return (+ <Tooltip title={String(value)}>+ <div className="truncate max-w-xs">{String(value)}</div>+ </Tooltip>+ )+}++function columnTitle(key: string): string {+ const spaced = key.replace(/_/g, ' ')+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}++function buildColumns(rows: AIEnrichmentRunRow[]): LemonTableColumns<AIEnrichmentRunRow> {+ const outputColumns = deriveOutputColumns(rows)+ const hasErrorRows = rows.some((row) => row.outputs === null)++ const columns: LemonTableColumns<AIEnrichmentRunRow> = [+ { title: 'Company', key: 'company', dataIndex: 'company' },+ {+ title: 'Domain',+ key: 'domain',+ render: (_, row) => row.domain ?? <span className="text-secondary">–</span>,+ },+ {+ title: 'Inputs sent',+ key: 'inputs',+ render: (_, row) => {+ const summary = summarizeInputs(row.inputs)+ return summary ? (+ <Tooltip title={summary}>+ <div className="truncate max-w-xs text-secondary text-xs">{summary}</div>+ </Tooltip>+ ) : (+ <span className="text-secondary">–</span>+ )+ },+ },+ ...outputColumns.map((column) => ({+ title: columnTitle(column.key),+ key: column.key,+ align: column.type === 'number' ? ('right' as const) : undefined,+ render: (_: unknown, row: AIEnrichmentRunRow) => outputCell(row, column),+ })),+ ]++ if (hasErrorRows) {+ columns.push({+ title: 'Error',+ key: 'error',+ render: (_, row) =>+ row.error ? (+ <Tooltip title={row.error}>+ <LemonTag type="danger">{summarizeError(row.error)}</LemonTag>+ </Tooltip>+ ) : null,+ })+ }++ return columns+}++export function AIEnrichmentResultsTable(): JSX.Element {+ const { runRows, runSummary, runError, isRunning } = useValues(aiEnrichmentLogic)++ const columns = buildColumns(runRows)++ return (+ <div className="space-y-2">+ {runError && (+ <LemonBanner type="error">+ <div>{summarizeError(runError)}</div>+ <div className="text-xs mt-1 opacity-75">{runError}</div>+ </LemonBanner>+ )}+ <LemonTable+ dataSource={runRows}+ columns={columns}+ loading={isRunning && runRows.length === 0}+ rowKey={(row, index) => `${row.company}-${index}`}+ emptyState="Run the classifier to see verdicts here."+ />+ {runSummary && (+ <div className="text-secondary text-sm">+ Classified {runSummary.classified} · Unknown {runSummary.unknown} · Errors {runSummary.errors}+ </div>+ )}+ </div>+ )+}diff --git a/products/growth/frontend/aiEnrichment/AIEnrichmentScene.test.tsx b/products/growth/frontend/aiEnrichment/AIEnrichmentScene.test.tsxnew file mode 100644index 000000000000..d7d8e055e4a2--- /dev/null+++ b/products/growth/frontend/aiEnrichment/AIEnrichmentScene.test.tsx@@ -0,0 +1,96 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import { LemonDialog } from '@posthog/lemon-ui'++import type { ConfigVersionApi } from '../generated/api.schemas'+import { AIEnrichmentVersionRail } from './AIEnrichmentScene'++jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn(), useValues: jest.fn() }))+jest.mock('@posthog/lemon-ui', () => ({+ ...jest.requireActual('@posthog/lemon-ui'),+ LemonDialog: { open: jest.fn(), openForm: jest.fn() },+}))++const ACTIVE_VERSION: ConfigVersionApi = {+ id: 'config-v1',+ name: 'test_label',+ version: 'v1',+ prompt_text: '',+ model: 'gpt-5-mini',+ input_fields: [],+ output_fields: [],+ is_active: true,+ created_by_email: null,+ created_at: '2024-01-01T00:00:00Z',+ has_results: false,+}+const DRAFT_VERSION: ConfigVersionApi = { ...ACTIVE_VERSION, id: 'config-v2', version: 'v2', is_active: false }++describe('AIEnrichmentVersionRail', () => {+ const activateVersion = jest.fn()+ const loadVersionIntoEditor = jest.fn()+ const open = LemonDialog.open as jest.Mock++ afterEach(cleanup)++ beforeEach(() => {+ ;[activateVersion, loadVersionIntoEditor, open].forEach((mockFn) => mockFn.mockClear())+ ;(useActions as jest.Mock).mockReturnValue({ activateVersion, loadVersionIntoEditor })+ })++ function renderRail(isEditorDirty: boolean): void {+ ;(useValues as jest.Mock).mockReturnValue({+ selectedLabel: 'test_label',+ versions: [ACTIVE_VERSION, DRAFT_VERSION],+ configsLoading: false,+ activeVersion: ACTIVE_VERSION,+ selectedVersionId: DRAFT_VERSION.id,+ activateResultLoading: false,+ isEditorDirty,+ })+ render(<AIEnrichmentVersionRail />)+ }++ it('shows the real active version in the header, not whichever version is being viewed', () => {+ renderRail(false)+ // selectedVersionId points at the draft (v2); the header must still read the active one.+ expect(document.querySelector('[data-attr="ai-enrichment-active-version"]')).toHaveTextContent('v1')+ })++ it('activates immediately, with no discard warning, when there are no unsaved edits', () => {+ renderRail(false)++ fireEvent.click(screen.getByText('Activate'))++ expect(open).toHaveBeenCalledTimes(1)+ const dialogConfig = open.mock.calls[0][0]+ expect(dialogConfig.description).not.toMatch(/discard|unsaved/i)+ expect(activateVersion).not.toHaveBeenCalled()+ // Clicking Activate must only ever open the confirm dialog, never select the row+ // underneath it - a broken closest('button') guard on the row's onClick would fire this+ // too and pass silently if this assertion weren't here.+ expect(loadVersionIntoEditor).not.toHaveBeenCalled()++ dialogConfig.primaryButton.onClick()+ expect(activateVersion).toHaveBeenCalledWith(DRAFT_VERSION.id)+ })++ it('warns that unsaved edits will be discarded before activating a different version', () => {+ renderRail(true)++ fireEvent.click(screen.getByText('Activate'))++ expect(open).toHaveBeenCalledTimes(1)+ const dialogConfig = open.mock.calls[0][0]+ expect(dialogConfig.description).toMatch(/discard/i)+ // The gate gives the user one more chance to back out - activating must not happen until+ // they click through the warning, not on the first click of the Activate button itself.+ expect(activateVersion).not.toHaveBeenCalled()++ dialogConfig.primaryButton.onClick()+ expect(activateVersion).toHaveBeenCalledWith(DRAFT_VERSION.id)+ })+})diff --git a/products/growth/frontend/aiEnrichment/AIEnrichmentScene.tsx b/products/growth/frontend/aiEnrichment/AIEnrichmentScene.tsxnew file mode 100644index 000000000000..301ca9652022--- /dev/null+++ b/products/growth/frontend/aiEnrichment/AIEnrichmentScene.tsx@@ -0,0 +1,494 @@+import { useActions, useValues } from 'kea'++import { IconPlus, IconTrash } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonDialog,+ LemonInput,+ LemonInputSelect,+ LemonSelect,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ Link,+} from '@posthog/lemon-ui'++import { AccessDenied } from 'lib/components/AccessDenied'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { CodeEditor } from 'lib/monaco/CodeEditor'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { type ConfigVersionApi, type LabelSummaryApi, OutputFieldTypeEnumApi } from '../generated/api.schemas'+import { growthAiEnrichmentRunCreateBodySampleMax } from '../generated/api.zod'+import { aiEnrichmentLogic } from './aiEnrichmentLogic'+import {+ outputFieldsDisabledReason,+ type AIEnrichmentOutputField,+ type AIEnrichmentOutputFieldType,+} from './aiEnrichmentOutputFields'+import { AIEnrichmentResultsTable } from './AIEnrichmentResultsTable'+import { suggestNextVersion } from './aiEnrichmentVersioning'++export const scene: SceneExport = {+ component: AIEnrichmentScene,+ logic: aiEnrichmentLogic,+}++// Derived from the generated enum so a new backend output type shows up in the picker on its own.+const OUTPUT_FIELD_TYPE_OPTIONS: { value: AIEnrichmentOutputFieldType; label: string }[] = Object.values(+ OutputFieldTypeEnumApi+).map((value) => ({ value, label: value.charAt(0).toUpperCase() + value.slice(1) }))++function AIEnrichmentLabelPicker(): JSX.Element {+ const { labels, labelsLoading } = useValues(aiEnrichmentLogic)+ const results = labels?.results ?? []++ const columns: LemonTableColumns<LabelSummaryApi> = [+ {+ title: 'Label',+ key: 'label',+ render: (_, row) => <Link to={urls.aiEnrichment(row.label)}>{row.label}</Link>,+ },+ { title: 'Versions', key: 'version_count', dataIndex: 'version_count' },+ {+ title: 'Active version',+ key: 'active_version',+ render: (_, row) => row.active_version ?? <span className="text-secondary">None</span>,+ },+ ]++ return (+ <div className="space-y-2">+ <h3 className="mb-0">Pick a label</h3>+ <LemonTable+ dataSource={results}+ loading={labelsLoading}+ rowKey={(row) => row.label}+ columns={columns}+ emptyState="No labels have any saved prompt configs yet."+ />+ </div>+ )+}++// Exported for AIEnrichmentScene.test.tsx - covers the Activate discard-confirm gate directly+// against this component rather than the full scene.+export function AIEnrichmentVersionRail(): JSX.Element {+ const {+ selectedLabel,+ versions,+ configsLoading,+ activeVersion,+ selectedVersionId,+ activateResultLoading,+ isEditorDirty,+ } = useValues(aiEnrichmentLogic)+ const { activateVersion, loadVersionIntoEditor } = useActions(aiEnrichmentLogic)++ const selectVersion = (version: ConfigVersionApi): void => {+ if (!isEditorDirty) {+ loadVersionIntoEditor(version)+ return+ }+ LemonDialog.open({+ title: 'Discard unsaved changes?',+ description: `Viewing version ${version.version} will discard your unsaved edits. Nothing is saved until you save as a new version.`,+ primaryButton: {+ children: 'Discard changes',+ status: 'danger',+ onClick: () => loadVersionIntoEditor(version),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const confirmActivate = (version: ConfigVersionApi): void => {+ // Activating reloads and re-selects the newly active version, which discards any unsaved+ // edit the same way selectVersion's dialog does - so the same warning applies here, not+ // just a plain "activate this?" prompt that silently drops the draft.+ LemonDialog.open({+ title: `Activate version ${version.version}?`,+ description: isEditorDirty+ ? 'This discards your unsaved edits and starts computing this version instead of the currently active one. Nothing is saved until you save as a new version.'+ : 'The batch runner will start computing this version instead of the currently active one.',+ primaryButton: {+ children: isEditorDirty ? 'Discard changes and activate' : 'Activate',+ status: isEditorDirty ? 'danger' : undefined,+ onClick: () => activateVersion(version.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const columns: LemonTableColumns<ConfigVersionApi> = [+ {+ title: 'Version',+ key: 'version',+ render: (_, version) => (+ <div className="flex items-center gap-1">+ <span className={version.id === selectedVersionId ? 'font-semibold' : undefined}>+ {version.version}+ </span>+ {version.is_active && <LemonTag type="success">ACTIVE</LemonTag>}+ </div>+ ),+ },+ {+ title: 'Created',+ key: 'created_at',+ render: (_, version) => (+ <span className="text-secondary text-xs">+ {version.created_by_email ?? 'system'} · <TZLabel time={version.created_at} />+ </span>+ ),+ },+ {+ title: '',+ key: 'actions',+ render: (_, version) =>+ version.is_active ? null : (+ <LemonButton+ type="secondary"+ size="small"+ disabledReason={activateResultLoading ? 'Activation in progress' : undefined}+ onClick={() => confirmActivate(version)}+ >+ Activate+ </LemonButton>+ ),+ },+ ]++ return (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <h3 className="mb-0">{selectedLabel}</h3>+ <span className="text-secondary text-xs">+ Live version:{' '}+ <span className="font-semibold" data-attr="ai-enrichment-active-version">+ {activeVersion ? activeVersion.version : 'None'}+ </span>+ </span>+ </div>+ <LemonTable+ dataSource={versions}+ loading={configsLoading}+ rowKey={(version) => version.id}+ columns={columns}+ emptyState="No versions saved yet for this label."+ onRow={(version) => ({+ // No explicit className: LemonTable's own TableRow already adds+ // cursor-pointer + a hover background whenever onRow returns an onClick.+ tabIndex: 0,+ role: 'button',+ 'aria-label': `View version ${version.version}`,+ onClick: (e) => {+ // The Activate button lives in this same row - let its own onClick fire+ // without also selecting the row underneath it.+ if ((e.target as HTMLElement).closest('button')) {+ return+ }+ selectVersion(version)+ },+ onKeyDown: (e) => {+ if ((e.target as HTMLElement).closest('button')) {+ return+ }+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ selectVersion(version)+ }+ },+ })}+ />+ </div>+ )+}++function AIEnrichmentOutputFieldsEditor(): JSX.Element {+ const { editorOutputFields } = useValues(aiEnrichmentLogic)+ const { addOutputField, removeOutputField, updateOutputField, seedDefaultOutputFields } =+ useActions(aiEnrichmentLogic)++ if (editorOutputFields.length === 0) {+ return (+ <div className="flex items-center gap-2">+ <span className="text-secondary text-sm">+ Output fields are what the model returns. Add at least one to save or test-run.+ </span>+ <LemonButton type="secondary" size="small" onClick={() => seedDefaultOutputFields()}>+ Start with verdict, confidence, reasoning+ </LemonButton>+ </div>+ )+ }++ return (+ <div className="space-y-1">+ {editorOutputFields.map((field: AIEnrichmentOutputField, index: number) => (+ <div key={index} className="flex items-center gap-2">+ <LemonInput+ className="flex-1"+ placeholder="key, e.g. ai_pilled"+ value={field.key}+ onChange={(key) => updateOutputField(index, { key })}+ />+ <LemonSelect+ value={field.type}+ onChange={(type) => type && updateOutputField(index, { type })}+ options={OUTPUT_FIELD_TYPE_OPTIONS}+ />+ <LemonInput+ className="flex-[2]"+ placeholder="Description shown to the model (optional)"+ value={field.description}+ onChange={(description) => updateOutputField(index, { description })}+ />+ <LemonButton+ icon={<IconTrash />}+ size="small"+ status="danger"+ onClick={() => removeOutputField(index)}+ tooltip="Remove field"+ />+ </div>+ ))}+ <LemonButton icon={<IconPlus />} size="small" type="secondary" onClick={() => addOutputField()}>+ Add field+ </LemonButton>+ </div>+ )+}++function AIEnrichmentEditorPanel(): JSX.Element {+ const { editorPromptText, editorModel, editorInputFields, isEditorDirty, modelOptions, selectedVersion } =+ useValues(aiEnrichmentLogic)+ const { setEditorPromptText, setEditorModel, setEditorInputFields } = useActions(aiEnrichmentLogic)++ return (+ <div className="space-y-2">+ {isEditorDirty && (+ <LemonBanner type="info">+ Unsaved changes. Versions are frozen once saved, so saving creates a new one.+ </LemonBanner>+ )}+ {selectedVersion && !selectedVersion.is_active && !isEditorDirty && (+ <LemonBanner type="warning">+ Viewing version {selectedVersion.version}, which is not the active version running in production.+ </LemonBanner>+ )}+ <div className="flex items-center gap-2">+ <span className="font-semibold">Model</span>+ <div className="w-64">+ <LemonInputSelect+ mode="single"+ size="small"+ value={editorModel ? [editorModel] : []}+ onChange={(values) => values[0] && setEditorModel(values[0])}+ options={modelOptions}+ placeholder="Search models..."+ data-attr="ai-enrichment-model"+ />+ </div>+ </div>+ <CodeEditor+ // Remount when a version loads: monaco can mount before async state hydrates and+ // miss the first controlled value update.+ key={selectedVersion?.id ?? 'unloaded'}+ className="border"+ language="markdown"+ value={editorPromptText}+ onChange={(value) => setEditorPromptText(value ?? '')}+ height={320}+ options={{ minimap: { enabled: false }, wordWrap: 'on' }}+ />+ <div className="space-y-1">+ <div className="font-semibold">Input fields</div>+ <div className="text-secondary text-xs">+ Dotted paths into the org's archived company-data snapshot (e.g. funding.fundingStage), passed to+ the prompt for each sampled org.+ </div>+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={editorInputFields}+ onChange={(fields) => setEditorInputFields(fields)}+ placeholder="Add a payload field and press enter..."+ data-attr="ai-enrichment-input-fields"+ />+ </div>+ <div className="space-y-1">+ <div className="font-semibold">Output fields</div>+ <div className="text-secondary text-xs">+ The keys, types, and optional descriptions the model must return for each sampled org.+ </div>+ <AIEnrichmentOutputFieldsEditor />+ </div>+ </div>+ )+}++function inputFieldsDisabledReason(fields: string[]): string | undefined {+ return fields.length > 0 ? undefined : 'Add at least one input field'+}++function runDisabledReason(+ canRun: boolean,+ editorPromptText: string,+ inputReason: string | undefined,+ outputReason: string | undefined+): string | undefined {+ if (canRun) {+ return undefined+ }+ if (!editorPromptText.trim()) {+ return 'Enter a prompt before running'+ }+ if (inputReason) {+ return `${inputReason} before running`+ }+ if (outputReason) {+ return `${outputReason} before running`+ }+ return undefined+}++function AIEnrichmentTestRunControls(): JSX.Element {+ const {+ sampleSize,+ canRun,+ isRunning,+ saveResultLoading,+ editorPromptText,+ editorInputFields,+ editorOutputFields,+ } = useValues(aiEnrichmentLogic)+ const { setSampleSize, runClassification } = useActions(aiEnrichmentLogic)+ const inputReason = inputFieldsDisabledReason(editorInputFields)+ const outputReason = outputFieldsDisabledReason(editorOutputFields)++ return (+ <div className="flex flex-wrap items-end gap-2">+ <div>+ <label className="text-xs font-semibold" htmlFor="ai-enrichment-sample-size">+ Sample size+ </label>+ <LemonInput+ id="ai-enrichment-sample-size"+ type="number"+ min={1}+ max={growthAiEnrichmentRunCreateBodySampleMax}+ value={sampleSize}+ onChange={(value) => setSampleSize(value ?? 1)}+ />+ </div>+ <LemonButton+ type="primary"+ loading={isRunning}+ disabledReason={+ saveResultLoading+ ? 'Save in progress'+ : runDisabledReason(canRun, editorPromptText, inputReason, outputReason)+ }+ onClick={() => runClassification()}+ data-attr="ai-enrichment-test-run"+ >+ Test run+ </LemonButton>+ <span className="text-secondary text-xs">+ Runs the prompt above (including unsaved edits) against the most recently archived orgs. Nothing is+ saved.+ </span>+ </div>+ )+}++function AIEnrichmentSaveControls(): JSX.Element {+ const { saveResultLoading, selectedLabel, isRunning, editorInputFields, editorOutputFields, versions } =+ useValues(aiEnrichmentLogic)+ const { saveVersion } = useActions(aiEnrichmentLogic)+ const inputReason = inputFieldsDisabledReason(editorInputFields)+ const outputReason = outputFieldsDisabledReason(editorOutputFields)++ return (+ <div className="flex items-center gap-2">+ <LemonButton+ type="secondary"+ loading={saveResultLoading}+ disabledReason={+ isRunning+ ? 'Test run in progress'+ : !selectedLabel+ ? 'Select a label first'+ : inputReason+ ? `${inputReason} before saving`+ : outputReason+ ? `${outputReason} before saving`+ : undefined+ }+ onClick={() =>+ LemonDialog.openForm({+ title: 'Save as new version',+ description:+ 'Versions are immutable once saved. Accept the suggested version, or pick your own.',+ initialValues: { version: suggestNextVersion(versions) },+ content: (+ <LemonField name="version" label="Version">+ <LemonInput autoFocus />+ </LemonField>+ ),+ errors: { version: (value) => (!value?.trim() ? 'Enter a version name' : undefined) },+ onSubmit: ({ version }) => saveVersion(version),+ })+ }+ data-attr="ai-enrichment-save"+ >+ Save as new version+ </LemonButton>+ <span className="text-secondary text-xs">+ Freezes the current prompt, model, inputs, and outputs into a new, immutable version.+ </span>+ </div>+ )+}++function AIEnrichmentEditor(): JSX.Element {+ return (+ <div className="flex gap-4">+ <div className="min-w-0 flex-1 space-y-4">+ <AIEnrichmentVersionRail />+ <AIEnrichmentEditorPanel />+ <AIEnrichmentTestRunControls />+ <AIEnrichmentSaveControls />+ <AIEnrichmentResultsTable />+ </div>+ </div>+ )+}++export function AIEnrichmentScene(): JSX.Element {+ const { user } = useValues(userLogic)+ const { selectedLabel } = useValues(aiEnrichmentLogic)++ if (!user?.is_staff) {+ return <AccessDenied object="page" reason="This page is only accessible to staff users." />+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name="AI enrichment"+ description="See which classifier version is live for a label, edit and test-run a draft, then save it as a new version and switch which one is live."+ resourceType={{ type: 'llm_analytics' }}+ />+ {selectedLabel ? <AIEnrichmentEditor /> : <AIEnrichmentLabelPicker />}+ </SceneContent>+ )+}diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.test.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.test.tsnew file mode 100644index 000000000000..73db898ccf1c--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.test.ts@@ -0,0 +1,298 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { urls } from 'scenes/urls'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { ConfigVersionApi } from '../generated/api.schemas'+import { aiEnrichmentLogic } from './aiEnrichmentLogic'++const CONFIG_V1: ConfigVersionApi = {+ id: 'config-v1',+ name: 'test_label',+ version: 'v1',+ prompt_text: 'original prompt',+ model: 'gpt-5-mini',+ input_fields: ['name'],+ output_fields: [{ key: 'verdict', type: 'boolean', description: '' }],+ is_active: true,+ created_by_email: '[email protected]',+ created_at: '2024-01-01T00:00:00Z',+ has_results: false,+}++// A real streamed Response, split mid-body across two chunks so the listener's buffer/line-split+// handling (not just JSON.parse of one clean line) is what's under test.+function ndjsonResponse(lines: string[]): Response {+ const body = lines.map((line) => line + '\n').join('')+ const bytes = new TextEncoder().encode(body)+ const mid = Math.floor(bytes.length / 2)+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(bytes.slice(0, mid))+ controller.enqueue(bytes.slice(mid))+ controller.close()+ },+ })+ return new Response(stream, { status: 200, headers: { 'Content-Type': 'application/x-ndjson' } })+}++describe('aiEnrichmentLogic', () => {+ let logic: ReturnType<typeof aiEnrichmentLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/growth_ai_enrichment/labels/': { results: [] },+ '/api/growth_ai_enrichment/models/': { results: [{ id: 'gpt-5-mini' }, { id: 'gpt-5-nano' }] },+ '/api/growth_ai_enrichment/configs/': { results: [CONFIG_V1] },+ },+ })+ initKeaTests()+ logic = aiEnrichmentLogic()+ logic.mount()+ })++ describe('URL label encoding', () => {+ it('decodes a URL-encoded label (built via urls.aiEnrichment) back to its raw form', async () => {+ const rawLabel = 'weird/label with spaces & stuff'++ await expectLogic(logic, () => {+ router.actions.push(urls.aiEnrichment(rawLabel))+ }).toFinishAllListeners()++ expect(logic.values.selectedLabel).toBe(rawLabel)+ })++ it('falls back to the raw value for malformed percent-encoding rather than crashing', async () => {+ await expectLogic(logic, () => {+ router.actions.push('/ai-enrichment/bad%zzlabel')+ }).toFinishAllListeners()++ expect(logic.values.selectedLabel).toBe('bad%zzlabel')+ })+ })++ describe('draft state machine', () => {+ it('loads a version into the editor as not dirty', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadVersionIntoEditor(CONFIG_V1)+ }).toMatchValues({+ editorPromptText: 'original prompt',+ editorModel: 'gpt-5-mini',+ editorInputFields: ['name'],+ isEditorDirty: false,+ })+ })++ it('marks the editor dirty the moment a loaded version is edited, and saving always targets a new version', async () => {+ logic.actions.loadVersionIntoEditor(CONFIG_V1)++ await expectLogic(logic, () => {+ logic.actions.setEditorPromptText('edited prompt')+ }).toMatchValues({ isEditorDirty: true })++ // Editing never mutates the loaded version's own fields - the draft is separate state,+ // which is what makes "save" always a create rather than an update.+ expect(CONFIG_V1.prompt_text).toBe('original prompt')+ })++ it('is dirty only once something is actually typed for a fresh, versionless label', () => {+ logic.actions.setSelectedLabel('brand_new_label')+ expect(logic.values.isEditorDirty).toBe(false)++ logic.actions.setEditorPromptText('a new prompt')+ expect(logic.values.isEditorDirty).toBe(true)+ })+ })++ describe('canRun', () => {+ it('requires a label, prompt, input field, and valid output field before a test run is allowed', () => {+ logic.actions.setSelectedLabel('test_label')+ expect(logic.values.canRun).toBe(false)++ logic.actions.setEditorPromptText('judge it')+ expect(logic.values.canRun).toBe(false)++ logic.actions.setEditorInputFields(['name'])+ expect(logic.values.canRun).toBe(false)++ logic.actions.addOutputField()+ logic.actions.updateOutputField(0, { key: 'verdict' })+ expect(logic.values.canRun).toBe(true)+ })+ })++ describe('saveVersion', () => {+ it('posts the current draft under the selected label at the chosen version, then selects it back in', async () => {+ let requestBody: unknown+ let saved = false+ const savedVersion: ConfigVersionApi = { ...CONFIG_V1, id: 'config-v2', version: 'v2', is_active: false }+ useMocks({+ get: {+ // Reflects the save in the label's version list, same as a real reload would -+ // the point under test is that the editor ends up pointed at the new row.+ '/api/growth_ai_enrichment/configs/': () => ({+ results: saved ? [CONFIG_V1, savedVersion] : [CONFIG_V1],+ }),+ },+ post: {+ '/api/growth_ai_enrichment/save/': async ({ request }) => {+ requestBody = await request.json()+ saved = true+ return [201, savedVersion]+ },+ },+ })+ // Let the label selection's own config load (and the loadVersionIntoEditor it+ // triggers) settle first, so it can't race with - and clobber - the edit below.+ await expectLogic(logic, () => {+ logic.actions.setSelectedLabel('test_label')+ }).toDispatchActions(['loadConfigsSuccess'])+ logic.actions.setEditorPromptText('a new prompt')++ await expectLogic(logic, () => {+ logic.actions.saveVersion('v2')+ }).toFinishAllListeners()++ expect(requestBody).toEqual({+ label: 'test_label',+ version: 'v2',+ prompt_text: 'a new prompt',+ model: 'gpt-5-mini',+ input_fields: ['name'],+ output_fields: [{ key: 'verdict', type: 'boolean', description: '' }],+ })+ expect(logic.values.selectedVersionId).toBe('config-v2')+ })+ })++ describe('runClassification', () => {+ it('parses ndjson rows and the trailing summary line out of a chunked stream', async () => {+ const rowLine = JSON.stringify({+ company: 'Acme',+ domain: 'acme.com',+ inputs: { name: 'Acme' },+ outputs: { verdict: true },+ })+ const summaryLine = JSON.stringify({ summary: { classified: 1, unknown: 0, errors: 0 } })+ useMocks({+ post: {+ '/api/growth_ai_enrichment/run/': () => ndjsonResponse([rowLine, summaryLine]),+ },+ })+ // Let the label selection's own config load (and the loadVersionIntoEditor it+ // triggers) settle first - loadVersionIntoEditor resets runRows/runSummary (see the+ // "stops a stale run" tests below), so a pending one racing the run below would wipe+ // out the very rows this test asserts on.+ await expectLogic(logic, () => {+ logic.actions.setSelectedLabel('test_label')+ }).toDispatchActions(['loadConfigsSuccess'])+ logic.actions.setEditorPromptText('judge it')+ logic.actions.setEditorInputFields(['name'])+ logic.actions.addOutputField()+ logic.actions.updateOutputField(0, { key: 'verdict' })++ await expectLogic(logic, () => {+ logic.actions.runClassification()+ }).toFinishAllListeners()++ expect(logic.values.runRows).toEqual([+ { company: 'Acme', domain: 'acme.com', inputs: { name: 'Acme' }, outputs: { verdict: true } },+ ])+ expect(logic.values.runSummary).toEqual({ classified: 1, unknown: 0, errors: 0 })+ expect(logic.values.isRunning).toBe(false)+ })++ it('surfaces a terminal aborted-run error and clears isRunning, without the generic fallback toast', async () => {+ const rowLine = JSON.stringify({+ company: 'Acme',+ domain: 'acme.com',+ inputs: { name: 'Acme' },+ outputs: { verdict: true },+ })+ const errorLine = JSON.stringify({ error: 'LLM gateway timed out', aborted: true })+ useMocks({+ post: {+ '/api/growth_ai_enrichment/run/': () => ndjsonResponse([rowLine, errorLine]),+ },+ })+ await expectLogic(logic, () => {+ logic.actions.setSelectedLabel('test_label')+ }).toDispatchActions(['loadConfigsSuccess'])+ logic.actions.setEditorPromptText('judge it')+ logic.actions.setEditorInputFields(['name'])+ logic.actions.addOutputField()+ logic.actions.updateOutputField(0, { key: 'verdict' })++ await expectLogic(logic, () => {+ logic.actions.runClassification()+ }).toFinishAllListeners()++ // The row emitted before the terminal error still lands - only the run as a whole is+ // marked failed, not the rows already streamed in.+ expect(logic.values.runRows).toEqual([+ { company: 'Acme', domain: 'acme.com', inputs: { name: 'Acme' }, outputs: { verdict: true } },+ ])+ expect(logic.values.runError).toBe('LLM gateway timed out')+ expect(logic.values.runSummary).toBeNull()+ expect(logic.values.isRunning).toBe(false)+ })++ it('is not callable again while a run is already in flight', async () => {+ useMocks({+ post: {+ '/api/growth_ai_enrichment/run/': () => ndjsonResponse([JSON.stringify({ summary: {} })]),+ },+ })+ await expectLogic(logic, () => {+ logic.actions.setSelectedLabel('test_label')+ }).toDispatchActions(['loadConfigsSuccess'])+ logic.actions.setEditorPromptText('judge it')+ logic.actions.setEditorInputFields(['name'])+ logic.actions.addOutputField()+ logic.actions.updateOutputField(0, { key: 'verdict' })++ logic.actions.runClassification()++ expect(logic.values.isRunning).toBe(true)+ expect(logic.values.canRun).toBe(false)+ })++ it('stops a stale run and clears its rows when the label changes mid-run', async () => {+ useMocks({+ post: {+ '/api/growth_ai_enrichment/run/': () => ndjsonResponse([JSON.stringify({ summary: {} })]),+ },+ })+ await expectLogic(logic, () => {+ logic.actions.setSelectedLabel('test_label')+ }).toDispatchActions(['loadConfigsSuccess'])+ logic.actions.setEditorPromptText('judge it')+ logic.actions.setEditorInputFields(['name'])+ logic.actions.addOutputField()+ logic.actions.updateOutputField(0, { key: 'verdict' })+ logic.actions.appendRunRow({ company: 'Stale Co', domain: null, inputs: {}, outputs: { verdict: true } })+ logic.actions.setIsRunning(true)++ logic.actions.setSelectedLabel('other_label')++ expect(logic.values.runRows).toEqual([])+ expect(logic.values.runSummary).toBeNull()+ expect(logic.values.isRunning).toBe(false)+ })++ it('stops a stale run and clears its rows when a different version is loaded mid-run', () => {+ logic.actions.appendRunRow({ company: 'Stale Co', domain: null, inputs: {}, outputs: { verdict: true } })+ logic.actions.setIsRunning(true)++ logic.actions.loadVersionIntoEditor(CONFIG_V1)++ expect(logic.values.runRows).toEqual([])+ expect(logic.values.runSummary).toBeNull()+ expect(logic.values.isRunning).toBe(false)+ })+ })+})diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.tsnew file mode 100644index 000000000000..9aaf513af4db--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentLogic.ts@@ -0,0 +1,770 @@+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)+ // Optional: an unmount mid-run already disposed everything (including this entry)+ // and nulled the registry (kea-disposables.ts's beforeUnmount) by the time this+ // finally block resumes after the abort it triggered - dispose() on null would+ // otherwise throw here as an unhandled rejection.+ 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)+ }+ },+ })),+])diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.test.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.test.tsnew file mode 100644index 000000000000..4e6d5dab97d2--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.test.ts@@ -0,0 +1,28 @@+import {+ AIEnrichmentOutputField,+ buildOutputFieldsPayload,+ hasValidOutputFields,+ outputFieldsDisabledReason,+} from './aiEnrichmentOutputFields'++const field = (key: string): AIEnrichmentOutputField => ({ key, type: 'boolean', description: '' })++describe('aiEnrichmentOutputFields', () => {+ it('drops half-typed rows from the payload, which the API rejects as an invalid key', () => {+ expect(buildOutputFieldsPayload([field('is_ai'), field(''), field(' ')])).toEqual([field('is_ai')])+ })++ it.each([+ [[], false],+ [[field('')], false],+ [[field(' ')], false],+ [[field(''), field('is_ai')], true],+ ])('%j has usable output fields: %s', (fields, expected) => {+ expect(hasValidOutputFields(fields)).toBe(expected)+ })++ it('gives a reason only while nothing usable is entered', () => {+ expect(outputFieldsDisabledReason([field('')])).toBe('Add at least one output field')+ expect(outputFieldsDisabledReason([field('is_ai')])).toBeUndefined()+ })+})diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.tsnew file mode 100644index 000000000000..10f5e9b56cea--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentOutputFields.ts@@ -0,0 +1,31 @@+import type { OutputFieldApi, OutputFieldTypeEnumApi } from '../generated/api.schemas'++export type AIEnrichmentOutputFieldType = OutputFieldTypeEnumApi++// The editor always carries a description (blank while unset), where the API leaves it optional.+export interface AIEnrichmentOutputField extends OutputFieldApi {+ description: string+}++// The classifier's whole output contract: these are the keys the prompt asks the model for and+// the only keys a stored verdict carries. The label is a human name and is never one of them, so+// renaming a label changes nothing about what a version computes.+export const DEFAULT_OUTPUT_FIELD_SEED: AIEnrichmentOutputField[] = [+ { key: 'verdict', type: 'boolean', description: 'Whether this company matches the label.' },+ { key: 'confidence', type: 'number', description: 'Confidence in the verdict, from 0 to 1.' },+ { key: 'reasoning', type: 'string', description: 'Brief reasoning for the verdict.' },+]++// Half-typed rows are a normal editor state, so they're dropped rather than sent. Save, run, and+// the enabled/disabled check all go through here so they can't disagree on what will be submitted.+export function buildOutputFieldsPayload(fields: AIEnrichmentOutputField[]): AIEnrichmentOutputField[] {+ return fields.filter((field) => field.key.trim().length > 0)+}++export function hasValidOutputFields(fields: AIEnrichmentOutputField[]): boolean {+ return buildOutputFieldsPayload(fields).length > 0+}++export function outputFieldsDisabledReason(fields: AIEnrichmentOutputField[]): string | undefined {+ return hasValidOutputFields(fields) ? undefined : 'Add at least one output field'+}diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.test.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.test.tsnew file mode 100644index 000000000000..6020aebec754--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.test.ts@@ -0,0 +1,92 @@+import type { AIEnrichmentRunRow } from './aiEnrichmentLogic'+import { deriveOutputColumns, isSkippedRow, summarizeError, summarizeInputs } from './aiEnrichmentResultColumns'++const row = (outputs: AIEnrichmentRunRow['outputs'], meta?: AIEnrichmentRunRow['meta']): AIEnrichmentRunRow => ({+ company: 'Acme',+ domain: 'acme.com',+ inputs: {},+ outputs,+ ...(meta ? { meta } : {}),+})++describe('aiEnrichmentResultColumns', () => {+ describe('isSkippedRow', () => {+ it("prefers meta.skipped, the backend's authoritative flag", () => {+ expect(isSkippedRow(row({ is_ai: true }, { skipped: 'missing or empty archived payload' }))).toBe(true)+ expect(isSkippedRow(row({ is_ai: true }, {}))).toBe(false)+ })++ it('falls back to sniffing for the literal "unknown" string when meta is absent', () => {+ expect(isSkippedRow(row({ is_ai: 'unknown' }))).toBe(true)+ expect(isSkippedRow(row({ is_ai: true }))).toBe(false)+ })+ })++ describe('deriveOutputColumns', () => {+ it('derives column key and type from the first row that has each key', () => {+ const rows = [row({ is_ai: true, confidence: 0.9, reasoning: 'because' })]+ expect(deriveOutputColumns(rows)).toEqual([+ { key: 'is_ai', type: 'boolean' },+ { key: 'confidence', type: 'number' },+ { key: 'reasoning', type: 'string' },+ ])+ })++ it('skips error rows, whose outputs is null', () => {+ const rows = [row(null), row({ is_ai: false })]+ expect(deriveOutputColumns(rows)).toEqual([{ key: 'is_ai', type: 'boolean' }])+ })++ it('returns nothing for an all-error result set', () => {+ expect(deriveOutputColumns([row(null)])).toEqual([])+ })++ it('does not let an "unknown" verdict decide a boolean column\'s type', () => {+ // If the first sampled row were skipped, taking its type from the literal string+ // "unknown" would mark the whole column "string" and misrender every later row's+ // real boolean under the wrong branch.+ const rows = [row({ is_ai: 'unknown' }), row({ is_ai: true })]+ expect(deriveOutputColumns(rows)).toEqual([{ key: 'is_ai', type: 'boolean' }])+ })++ it('falls back to string for a key that is "unknown" in every sampled row', () => {+ expect(deriveOutputColumns([row({ is_ai: 'unknown' })])).toEqual([{ key: 'is_ai', type: 'string' }])+ })++ it('treats a meta.skipped row as skipped even for a field whose skipped value is null rather than "unknown"', () => {+ // Only the boolean verdict field (if any) gets the literal "unknown" string on a+ // skipped row (enrichment/labels.py's unknown_output); every other configured field+ // is just null. Without meta.skipped, a null first value would still get typed+ // "string" here (typeOfValue's default) and misrender every later row's real number.+ const skippedOutputs = { headcount: null } as unknown as AIEnrichmentRunRow['outputs']+ const rows = [row(skippedOutputs, { skipped: 'missing or empty archived payload' }), row({ headcount: 12 })]+ expect(deriveOutputColumns(rows)).toEqual([{ key: 'headcount', type: 'number' }])+ })+ })++ describe('summarizeInputs', () => {+ it('joins fields sent to the LLM into one line', () => {+ expect(summarizeInputs({ name: 'Acme', 'funding.fundingStage': 'seed' })).toBe(+ 'name: Acme, funding.fundingStage: seed'+ )+ })++ it('is blank when nothing was sent (e.g. an unknown/skipped verdict)', () => {+ expect(summarizeInputs({})).toBe('')+ })+ })++ describe('summarizeError', () => {+ it('maps a recognized exception pattern to a plain-language summary', () => {+ expect(summarizeError('AuthenticationError: litellm.AuthenticationError: Incorrect API key')).toBe(+ 'Authentication failed for this model. Check the API key configuration.'+ )+ })++ it('falls back to the raw error text when nothing matches', () => {+ expect(summarizeError('SomeWeirdError: unrecognized failure shape')).toBe(+ 'SomeWeirdError: unrecognized failure shape'+ )+ })+ })+})diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.tsnew file mode 100644index 000000000000..3bb88412dad4--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentResultColumns.ts@@ -0,0 +1,96 @@+import type { AIEnrichmentRunRow } from './aiEnrichmentLogic'+import type { AIEnrichmentOutputFieldType } from './aiEnrichmentOutputFields'++export interface OutputColumnSpec {+ key: string+ type: AIEnrichmentOutputFieldType+}++// The runner's sentinel for a skipped/indeterminate verdict (enrichment/labels.py's UNKNOWN),+// written into any output key regardless of that key's declared type - most visibly a boolean+// one, where the raw string "unknown" is truthy and would otherwise render as a green success tag+// indistinguishable from a real positive. Kept only as a fallback (see isSkippedRow) - a schema+// with no boolean output field never writes this sentinel into any value at all.+export const UNKNOWN_VERDICT = 'unknown'++// The authoritative "was this row's verdict skipped" check (mirrors labels.py's+// is_unknown_output). Falls back to sniffing individual values for the literal "unknown" string+// only when `meta` is absent - older cached rows, or a stream from before this field existed.+export function isSkippedRow(row: AIEnrichmentRunRow): boolean {+ if (row.meta) {+ return Boolean(row.meta.skipped)+ }+ return Object.values(row.outputs ?? {}).some((value) => value === UNKNOWN_VERDICT)+}++function typeOfValue(value: boolean | number | string): AIEnrichmentOutputFieldType {+ if (typeof value === 'boolean') {+ return 'boolean'+ }+ if (typeof value === 'number') {+ return 'number'+ }+ return 'string'+}++// Columns are derived from the ndjson rows themselves rather than the editor's output_fields, so+// the results table renders correctly for both a live run (draft output_fields) and any future+// read of a saved version's results. Column order follows first-seen key order, which matches the+// backend's dict insertion order in format_run_row.+export function deriveOutputColumns(rows: AIEnrichmentRunRow[]): OutputColumnSpec[] {+ const order: string[] = []+ const typeByKey = new Map<string, AIEnrichmentOutputFieldType>()+ for (const row of rows) {+ if (!row.outputs) {+ continue+ }+ const rowSkipped = isSkippedRow(row)+ for (const [key, value] of Object.entries(row.outputs)) {+ if (!order.includes(key)) {+ order.push(key)+ }+ // A skipped row's values say nothing about the column's real type - if the first row+ // seen for a key were skipped, taking its type from that value would misrender every+ // later row's real boolean/number as a plain string. Keep scanning until a row+ // supplies an actual typed value.+ if (!typeByKey.has(key) && !rowSkipped && value !== UNKNOWN_VERDICT) {+ typeByKey.set(key, typeOfValue(value))+ }+ }+ }+ // A key seen only in skipped rows still needs a column; string is a reasonable default+ // renderer for it.+ return order.map((key) => ({ key, type: typeByKey.get(key) ?? 'string' }))+}++// A one-line summary of what was actually sent to the LLM for this row (post domain reduction),+// for the compact "Inputs" column - the full detail lives in the per-field tooltip the caller+// renders separately.+export function summarizeInputs(inputs: Record<string, unknown>): string {+ const entries = Object.entries(inputs)+ if (entries.length === 0) {+ return ''+ }+ return entries.map(([key, value]) => `${key}: ${value}`).join(', ')+}++// Pattern-matched plain-language summaries for the raw exception text backend/lab.py's+// _run_error renders (e.g. "AuthenticationError: litellm.AuthenticationError: ..."). The row's+// full raw error stays available in the cell's hover tooltip; this is only what's shown by+// default, so a staff user doesn't have to parse an SDK exception repr to know what to do next.+const ERROR_SUMMARIES: { pattern: RegExp; summary: string }[] = [+ {+ pattern: /AuthenticationError|\b401\b/i,+ summary: 'Authentication failed for this model. Check the API key configuration.',+ },+ { pattern: /RateLimitError|\b429\b/i, summary: 'Rate limited by the model provider. Try again in a moment.' },+ {+ pattern: /APIConnectionError|Connection error|ECONNREFUSED/i,+ summary: "Couldn't reach the model gateway. Check the network connection.",+ },+ { pattern: /Timeout|timed out/i, summary: 'The model call timed out. Try again.' },+]++export function summarizeError(error: string): string {+ return ERROR_SUMMARIES.find(({ pattern }) => pattern.test(error))?.summary ?? error+}diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.test.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.test.tsnew file mode 100644index 000000000000..e9c8da6c0b19--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.test.ts@@ -0,0 +1,30 @@+import type { ConfigVersionApi } from '../generated/api.schemas'+import { suggestNextVersion } from './aiEnrichmentVersioning'++const version = (version: string): ConfigVersionApi =>+ ({+ version,+ }) as ConfigVersionApi++describe('suggestNextVersion', () => {+ it('suggests v1 for a label with no versions yet', () => {+ expect(suggestNextVersion([])).toBe('v1')+ })++ it('bumps the highest numbered suffix, not the version count', () => {+ expect(suggestNextVersion([version('v1'), version('v2'), version('v3')])).toBe('v4')+ })++ it('ignores gaps left by a deleted version and never reuses a retired string', () => {+ expect(suggestNextVersion([version('v1'), version('v3')])).toBe('v4')+ })++ it('finds a v<n> suffix anywhere in a legacy-named version, not just an exact v<n> match', () => {+ expect(suggestNextVersion([version('ai-pilled-clay-v1')])).toBe('v2')+ expect(suggestNextVersion([version('ai-pilled-clay-v1'), version('ai-pilled-v2-draft')])).toBe('v3')+ })++ it('falls back to one past the version count when nothing has a numeric v suffix at all', () => {+ expect(suggestNextVersion([version('alpha'), version('beta')])).toBe('v3')+ })+})diff --git a/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.ts b/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.tsnew file mode 100644index 000000000000..32f3e1509890--- /dev/null+++ b/products/growth/frontend/aiEnrichment/aiEnrichmentVersioning.ts@@ -0,0 +1,20 @@+import type { ConfigVersionApi } from '../generated/api.schemas'++const VERSION_SUFFIX_RE = /v(\d+)/g++// Mirrors the server's suggestion (_next_version in api/ai_enrichment.py): the highest `v<digits>`+// occurring anywhere in any existing version string for this label, plus one - so a legacy name+// like "ai-pilled-clay-v1" still contributes its 1, not just an exact "v1". Falls back to one past+// the version count only when nothing on record has a v<n> pattern at all. The server has the+// last word - it re-derives this itself from a row lock and accepts a caller-supplied version+// regardless - so a client/server mismatch here (e.g. a version saved outside this UI) only+// changes the prefilled suggestion, never what's allowed.+export function suggestNextVersion(versions: ConfigVersionApi[]): string {+ let highest: number | null = null+ for (const version of versions) {+ for (const match of version.version.matchAll(VERSION_SUFFIX_RE)) {+ highest = Math.max(highest ?? 0, parseInt(match[1], 10))+ }+ }+ return highest !== null ? `v${highest + 1}` : `v${versions.length + 1}`+}diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex 01574d91cbae..128692e56756 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -7,6 +7,163 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface ActivateRequestApi {+ /** Prompt config id to activate for its label. */+ config_id: string+}++/**+ * * `boolean` - boolean+ * * `number` - number+ * * `string` - string+ */+export type OutputFieldTypeEnumApi = (typeof OutputFieldTypeEnumApi)[keyof typeof OutputFieldTypeEnumApi]++export const OutputFieldTypeEnumApi = {+ Boolean: 'boolean',+ Number: 'number',+ String: 'string',+} as const++export interface OutputFieldApi {+ /**+ * Output key, e.g. ai_pilled. Lowercase, starts with a letter, letters/digits/underscore only.+ * @pattern ^[a-z][a-z0-9_]*$+ */+ key: string+ /** Value type the LLM must return for this key.+ *+ * * `boolean` - boolean+ * * `number` - number+ * * `string` - string */+ type: OutputFieldTypeEnumApi+ /**+ * Shown to the LLM to describe what this key means. At most 400 characters.+ * @maxLength 400+ */+ description?: string+}++export interface ConfigVersionApi {+ /** Prompt config row id. */+ id: string+ /** Label this config computes, e.g. ai_pilled. */+ name: string+ /** Server-assigned version identity, e.g. v3. */+ version: string+ /** System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters. */+ prompt_text: string+ /** Gateway model id this version was authored against. */+ model: string+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields: string[]+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputFieldApi[]+ /** Whether the batch runner currently computes this version. */+ is_active: boolean+ /**+ * Email of the staff user who created this version, or null for system-seeded rows.+ * @nullable+ */+ readonly created_by_email: string | null+ /** When this version was created. */+ created_at: string+ /** Whether any EnrichmentLabelResult rows reference this version. Informational only: the API never edits a version's content in place, it only creates a new one, so this doesn't gate anything. The label name is not part of a version's content and can always be renamed. */+ readonly has_results: boolean+}++export interface ErrorResponseApi {+ /** Error message */+ error: string+}++export interface ConfigListResponseApi {+ /** Versions for the requested label, newest first. */+ results: ConfigVersionApi[]+}++export interface LabelSummaryApi {+ /** Label name computed by one or more prompt config versions. */+ label: string+ /** Number of prompt config versions saved for this label. */+ version_count: number+ /**+ * Version string the batch runner currently computes for this label, or null.+ * @nullable+ */+ active_version: string | null+}++export interface LabelListResponseApi {+ /** Distinct labels, alphabetical. */+ results: LabelSummaryApi[]+}++export interface GatewayModelApi {+ /** Gateway model id, usable as `model` on save/run. */+ id: string+}++export interface GatewayModelListResponseApi {+ /** Models the gateway currently lists (cached for 5 minutes), or empty if it is unreachable - there is no curated mirror, since one goes stale silently. */+ results: GatewayModelApi[]+}++export interface RunRequestApi {+ /**+ * Label this draft config computes, e.g. ai_pilled. Need not already exist - run classifies against an in-memory config only and persists nothing.+ * @maxLength 128+ */+ label: string+ /**+ * System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.+ * @maxLength 20000+ */+ prompt_text: string+ /**+ * Gateway model to classify with, routed through the LLM gateway. See GET /models/ for what it serves.+ * @maxLength 128+ */+ model: string+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields?: string[]+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputFieldApi[]+ /**+ * Number of the most recently archived, distinct orgs to classify (1-10). Each sampled org costs one LLM call, so keep this bounded during iteration.+ * @minimum 1+ * @maximum 10+ */+ sample?: number+}++export interface SaveRequestApi {+ /**+ * Label this config computes, e.g. ai_pilled.+ * @maxLength 128+ */+ label: string+ /**+ * Version identity for the new row, e.g. v3. Optional: omit (or send blank) to accept the server-suggested next version for this label. Versions are immutable once created - there is no update endpoint - and (label, version) must be unique.+ * @maxLength 128+ */+ version?: string+ /**+ * System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.+ * @maxLength 20000+ */+ prompt_text: string+ /**+ * Gateway model to classify with, routed through the LLM gateway. See GET /models/ for what it serves.+ * @maxLength 128+ */+ model: string+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields?: string[]+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputFieldApi[]+}+export interface ProductPushCampaignApi {/** Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it. */readonly id: string@@ -419,6 +576,26 @@ export interface SdkHealthReportApi {sdks: SdkAssessmentApi[]}+export type GrowthAiEnrichmentConfigsRetrieveParams = {+ /**+ * Label name to list prompt config versions for.+ * @minLength 1+ */+ label: string+}++export type GrowthAiEnrichmentRunCreateParams = {+ format?: GrowthAiEnrichmentRunCreateFormat+}++export type GrowthAiEnrichmentRunCreateFormat =+ (typeof GrowthAiEnrichmentRunCreateFormat)[keyof typeof GrowthAiEnrichmentRunCreateFormat]++export const GrowthAiEnrichmentRunCreateFormat = {+ Json: 'json',+ Ndjson: 'ndjson',+} as const+export type ProductPushCampaignActiveRetrieveParams = {/*** Team id of the project the caller is viewing. When that project already uses the campaign's product, the response is 204 so the promo isn't shown there.diff --git a/products/growth/frontend/generated/api.ts b/products/growth/frontend/generated/api.tsindex 6e08166545c3..64cbc0089f8d 100644--- a/products/growth/frontend/generated/api.ts+++ b/products/growth/frontend/generated/api.ts@@ -9,15 +9,177 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ActivateRequestApi,+ ConfigListResponseApi,+ ConfigVersionApi,+ GatewayModelListResponseApi,+ GrowthAiEnrichmentConfigsRetrieveParams,+ GrowthAiEnrichmentRunCreateParams,IdentityMatchingLinksListParams,IdentityMatchingLinksResponseApi,IdentityMatchingRunsResponseApi,+ LabelListResponseApi,ProductPushCampaignActiveRetrieveParams,ProductPushCampaignApi,+ RunRequestApi,+ SaveRequestApi,SdkHealthReportApi,SdkHealthReportRetrieveParams,} from './api.schemas'+export const getGrowthAiEnrichmentActivateCreateUrl = () => {+ return `/api/growth_ai_enrichment/activate/`+}++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentActivateCreate = async (+ activateRequestApi: ActivateRequestApi,+ options?: RequestInit+): Promise<ConfigVersionApi> => {+ return apiMutator<ConfigVersionApi>(getGrowthAiEnrichmentActivateCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(activateRequestApi),+ })+}++export const getGrowthAiEnrichmentConfigsRetrieveUrl = (params: GrowthAiEnrichmentConfigsRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/growth_ai_enrichment/configs/?${stringifiedParams}`+ : `/api/growth_ai_enrichment/configs/`+}++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentConfigsRetrieve = async (+ params: GrowthAiEnrichmentConfigsRetrieveParams,+ options?: RequestInit+): Promise<ConfigListResponseApi> => {+ return apiMutator<ConfigListResponseApi>(getGrowthAiEnrichmentConfigsRetrieveUrl(params), {+ ...options,+ method: 'GET',+ })+}++export const getGrowthAiEnrichmentLabelsRetrieveUrl = () => {+ return `/api/growth_ai_enrichment/labels/`+}++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentLabelsRetrieve = async (options?: RequestInit): Promise<LabelListResponseApi> => {+ return apiMutator<LabelListResponseApi>(getGrowthAiEnrichmentLabelsRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getGrowthAiEnrichmentModelsRetrieveUrl = () => {+ return `/api/growth_ai_enrichment/models/`+}++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentModelsRetrieve = async (options?: RequestInit): Promise<GatewayModelListResponseApi> => {+ return apiMutator<GatewayModelListResponseApi>(getGrowthAiEnrichmentModelsRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getGrowthAiEnrichmentRunCreateUrl = (params?: GrowthAiEnrichmentRunCreateParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/growth_ai_enrichment/run/?${stringifiedParams}`+ : `/api/growth_ai_enrichment/run/`+}++/**+ * One JSON object per line: a {company, domain, inputs, outputs: {<key>: value, ...}, meta} row as each LLM call completes, keyed by the submitted output_fields, then a final {summary: {classified, unknown, errors}} line. A run that fails partway ends with {error, aborted: true} instead of a summary. Persists nothing - spends real LLM money, so sample is capped at 10 and the endpoint is rate limited.+ * @summary Stream classifier verdicts for an unsaved draft config against recently archived orgs.+ */+export const growthAiEnrichmentRunCreate = async (+ runRequestApi: RunRequestApi,+ params?: GrowthAiEnrichmentRunCreateParams,+ options?: RequestInit+): Promise<Response> => {+ return apiMutator<Response>(getGrowthAiEnrichmentRunCreateUrl(params), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/x-ndjson', ...options?.headers },+ body: JSON.stringify(runRequestApi),+ })+}++export const getGrowthAiEnrichmentSaveCreateUrl = () => {+ return `/api/growth_ai_enrichment/save/`+}++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentSaveCreate = async (+ saveRequestApi: SaveRequestApi,+ options?: RequestInit+): Promise<ConfigVersionApi> => {+ return apiMutator<ConfigVersionApi>(getGrowthAiEnrichmentSaveCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(saveRequestApi),+ })+}+export const getProductPushCampaignActiveRetrieveUrl = (organizationId: string,params?: ProductPushCampaignActiveRetrieveParamsdiff --git a/products/growth/frontend/generated/api.zod.ts b/products/growth/frontend/generated/api.zod.tsindex e8a15d4e1b52..97ebaf54ea73 100644--- a/products/growth/frontend/generated/api.zod.ts+++ b/products/growth/frontend/generated/api.zod.ts@@ -7,3 +7,170 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+import * as zod from 'zod'++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const GrowthAiEnrichmentActivateCreateBody = /* @__PURE__ */ zod.object({+ config_id: zod.uuid().describe('Prompt config id to activate for its label.'),+})++/**+ * One JSON object per line: a {company, domain, inputs, outputs: {<key>: value, ...}, meta} row as each LLM call completes, keyed by the submitted output_fields, then a final {summary: {classified, unknown, errors}} line. A run that fails partway ends with {error, aborted: true} instead of a summary. Persists nothing - spends real LLM money, so sample is capped at 10 and the endpoint is rate limited.+ * @summary Stream classifier verdicts for an unsaved draft config against recently archived orgs.+ */+export const growthAiEnrichmentRunCreateBodyLabelMax = 128++export const growthAiEnrichmentRunCreateBodyPromptTextMax = 20000++export const growthAiEnrichmentRunCreateBodyModelMax = 128++export const growthAiEnrichmentRunCreateBodyOutputFieldsItemKeyRegExp = new RegExp('^[a-z][a-z0-9_]\*$')+export const growthAiEnrichmentRunCreateBodyOutputFieldsItemDescriptionDefault = ``+export const growthAiEnrichmentRunCreateBodyOutputFieldsItemDescriptionMax = 400++export const growthAiEnrichmentRunCreateBodySampleDefault = 5+export const growthAiEnrichmentRunCreateBodySampleMax = 10++export const GrowthAiEnrichmentRunCreateBody = /* @__PURE__ */ zod.object({+ label: zod+ .string()+ .max(growthAiEnrichmentRunCreateBodyLabelMax)+ .describe(+ 'Label this draft config computes, e.g. ai_pilled. Need not already exist - run classifies against an in-memory config only and persists nothing.'+ ),+ prompt_text: zod+ .string()+ .max(growthAiEnrichmentRunCreateBodyPromptTextMax)+ .describe(+ 'System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.'+ ),+ model: zod+ .string()+ .max(growthAiEnrichmentRunCreateBodyModelMax)+ .describe(+ 'Gateway model to classify with, routed through the LLM gateway. See GET \/models\/ for what it serves.'+ ),+ input_fields: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional.'+ ),+ output_fields: zod+ .array(+ zod.object({+ key: zod+ .string()+ .regex(growthAiEnrichmentRunCreateBodyOutputFieldsItemKeyRegExp)+ .describe(+ 'Output key, e.g. ai_pilled. Lowercase, starts with a letter, letters\/digits\/underscore only.'+ ),+ type: zod+ .enum(['boolean', 'number', 'string'])+ .describe('\* `boolean` - boolean\n\* `number` - number\n\* `string` - string')+ .describe(+ 'Value type the LLM must return for this key.\n\n\* `boolean` - boolean\n\* `number` - number\n\* `string` - string'+ ),+ description: zod+ .string()+ .max(growthAiEnrichmentRunCreateBodyOutputFieldsItemDescriptionMax)+ .default(growthAiEnrichmentRunCreateBodyOutputFieldsItemDescriptionDefault)+ .describe('Shown to the LLM to describe what this key means. At most 400 characters.'),+ })+ )+ .describe(+ "Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]\*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields."+ ),+ sample: zod+ .number()+ .min(1)+ .max(growthAiEnrichmentRunCreateBodySampleMax)+ .default(growthAiEnrichmentRunCreateBodySampleDefault)+ .describe(+ 'Number of the most recently archived, distinct orgs to classify (1-10). Each sampled org costs one LLM call, so keep this bounded during iteration.'+ ),+})++/**+ * Staff-only, unscoped API for the enrichment AI enrichment: browse labels and their prompt+ * config versions, test-run a draft config against recently archived orgs, save a new+ * immutable version, and flip which version is active.+ *+ * Registered on the root router so it is not team-nested - prompt configs are instance-global,+ * not scoped to any team or org.+ */+export const growthAiEnrichmentSaveCreateBodyLabelMax = 128++export const growthAiEnrichmentSaveCreateBodyVersionMax = 128++export const growthAiEnrichmentSaveCreateBodyPromptTextMax = 20000++export const growthAiEnrichmentSaveCreateBodyModelMax = 128++export const growthAiEnrichmentSaveCreateBodyOutputFieldsItemKeyRegExp = new RegExp('^[a-z][a-z0-9_]\*$')+export const growthAiEnrichmentSaveCreateBodyOutputFieldsItemDescriptionDefault = ``+export const growthAiEnrichmentSaveCreateBodyOutputFieldsItemDescriptionMax = 400++export const GrowthAiEnrichmentSaveCreateBody = /* @__PURE__ */ zod.object({+ label: zod+ .string()+ .max(growthAiEnrichmentSaveCreateBodyLabelMax)+ .describe('Label this config computes, e.g. ai_pilled.'),+ version: zod+ .string()+ .max(growthAiEnrichmentSaveCreateBodyVersionMax)+ .optional()+ .describe(+ 'Version identity for the new row, e.g. v3. Optional: omit (or send blank) to accept the server-suggested next version for this label. Versions are immutable once created - there is no update endpoint - and (label, version) must be unique.'+ ),+ prompt_text: zod+ .string()+ .max(growthAiEnrichmentSaveCreateBodyPromptTextMax)+ .describe(+ 'System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.'+ ),+ model: zod+ .string()+ .max(growthAiEnrichmentSaveCreateBodyModelMax)+ .describe(+ 'Gateway model to classify with, routed through the LLM gateway. See GET \/models\/ for what it serves.'+ ),+ input_fields: zod+ .array(zod.string())+ .optional()+ .describe(+ 'Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional.'+ ),+ output_fields: zod+ .array(+ zod.object({+ key: zod+ .string()+ .regex(growthAiEnrichmentSaveCreateBodyOutputFieldsItemKeyRegExp)+ .describe(+ 'Output key, e.g. ai_pilled. Lowercase, starts with a letter, letters\/digits\/underscore only.'+ ),+ type: zod+ .enum(['boolean', 'number', 'string'])+ .describe('\* `boolean` - boolean\n\* `number` - number\n\* `string` - string')+ .describe(+ 'Value type the LLM must return for this key.\n\n\* `boolean` - boolean\n\* `number` - number\n\* `string` - string'+ ),+ description: zod+ .string()+ .max(growthAiEnrichmentSaveCreateBodyOutputFieldsItemDescriptionMax)+ .default(growthAiEnrichmentSaveCreateBodyOutputFieldsItemDescriptionDefault)+ .describe('Shown to the LLM to describe what this key means. At most 400 characters.'),+ })+ )+ .describe(+ "Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]\*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields."+ ),+})diff --git a/products/growth/manifest.tsx b/products/growth/manifest.tsxindex 1aee2e6aef48..b148db747b14 100644--- a/products/growth/manifest.tsx+++ b/products/growth/manifest.tsx@@ -17,12 +17,20 @@ export const manifest: ProductManifest = {'Review probable links between anonymous visitors and identified persons, recovered from first-party signals.',iconType: 'persons',},+ AIEnrichment: {+ name: 'AI enrichment',+ import: () => import('./frontend/aiEnrichment/AIEnrichmentScene'),+ instanceLevel: true,+ },},routes: {'/identity-matching': ['IdentityMatching', 'identityMatching'],+ '/ai-enrichment': ['AIEnrichment', 'aiEnrichment'],+ '/ai-enrichment/:label': ['AIEnrichment', 'aiEnrichment'],},urls: {identityMatching: (): string => '/identity-matching',+ aiEnrichment: (label?: string): string => `/ai-enrichment${label ? `/${encodeURIComponent(label)}` : ''}`,},treeItemsProducts: [{diff --git a/products/growth/package.json b/products/growth/package.jsonindex 22536e4ccbaa..e6965988db01 100644--- a/products/growth/package.json+++ b/products/growth/package.json@@ -5,11 +5,19 @@},"dependencies": {"kea": "catalog:",- "kea-loaders": "catalog:"+ "kea-loaders": "catalog:",+ "kea-router": "catalog:"+ },+ "devDependencies": {+ "@testing-library/jest-dom": "^5.17.0",+ "@testing-library/react": "^14.3.1",+ "kea-test-utils": "catalog:"},"peerDependencies": {"@posthog/icons": "catalog:","@storybook/react": "catalog:",+ "@testing-library/jest-dom": "*",+ "@testing-library/react": "*","@types/react": "*","clsx": "*","jest": "*",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5b34bad038fb..af0f50e9bda4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2205,6 +2205,11 @@ export namespace Schemas {hideAggregation?: boolean | null;}+ export interface ActivateRequest {+ /** Prompt config id to activate for its label. */+ config_id: string;+ }+export interface ActivateVersionRequest {/** Version number to activate. Must reference an existing version of this app. */version_number: number;@@ -16213,6 +16218,72 @@ export namespace Schemas {Invalid: 'invalid',} as const;+ /**+ * * `boolean` - boolean+ * * `number` - number+ * * `string` - string+ */+ export type OutputFieldTypeEnum = typeof OutputFieldTypeEnum[keyof typeof OutputFieldTypeEnum];+++ export const OutputFieldTypeEnum = {+ Boolean: 'boolean',+ Number: 'number',+ String: 'string',+ } as const;++ export interface OutputField {+ /**+ * Output key, e.g. ai_pilled. Lowercase, starts with a letter, letters/digits/underscore only.+ * @pattern ^[a-z][a-z0-9_]*$+ */+ key: string;+ /** Value type the LLM must return for this key.+ *+ * * `boolean` - boolean+ * * `number` - number+ * * `string` - string */+ type: OutputFieldTypeEnum;+ /**+ * Shown to the LLM to describe what this key means. At most 400 characters.+ * @maxLength 400+ */+ description?: string;+ }++ export interface ConfigVersion {+ /** Prompt config row id. */+ id: string;+ /** Label this config computes, e.g. ai_pilled. */+ name: string;+ /** Server-assigned version identity, e.g. v3. */+ version: string;+ /** System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters. */+ prompt_text: string;+ /** Gateway model id this version was authored against. */+ model: string;+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields: string[];+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputField[];+ /** Whether the batch runner currently computes this version. */+ is_active: boolean;+ /**+ * Email of the staff user who created this version, or null for system-seeded rows.+ * @nullable+ */+ readonly created_by_email: string | null;+ /** When this version was created. */+ created_at: string;+ /** Whether any EnrichmentLabelResult rows reference this version. Informational only: the API never edits a version's content in place, it only creates a new one, so this doesn't gate anything. The label name is not part of a version's content and can always be renamed. */+ readonly has_results: boolean;+ }++ export interface ConfigListResponse {+ /** Versions for the requested label, newest first. */+ results: ConfigVersion[];+ }+/*** * `posthog_code` - posthog_code*/@@ -35429,6 +35500,16 @@ export namespace Schemas {revoked_server_ids: string[];}+ export interface GatewayModel {+ /** Gateway model id, usable as `model` on save/run. */+ id: string;+ }++ export interface GatewayModelListResponse {+ /** Models the gateway currently lists (cached for 5 minutes), or empty if it is unreachable - there is no curated mirror, since one goes stale silently. */+ results: GatewayModel[];+ }+/*** * `team` - Team default* * `member` - Member@@ -41532,6 +41613,23 @@ export namespace Schemas {max_tags?: number | null;}+ export interface LabelSummary {+ /** Label name computed by one or more prompt config versions. */+ label: string;+ /** Number of prompt config versions saved for this label. */+ version_count: number;+ /**+ * Version string the batch runner currently computes for this label, or null.+ * @nullable+ */+ active_version: string | null;+ }++ export interface LabelListResponse {+ /** Distinct labels, alphabetical. */+ results: LabelSummary[];+ }+/*** * `today` - today* * `this_week` - this_week@@ -67309,6 +67407,34 @@ export namespace Schemas {readonly created_at: string;}+ export interface RunRequest {+ /**+ * Label this draft config computes, e.g. ai_pilled. Need not already exist - run classifies against an in-memory config only and persists nothing.+ * @maxLength 128+ */+ label: string;+ /**+ * System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.+ * @maxLength 20000+ */+ prompt_text: string;+ /**+ * Gateway model to classify with, routed through the LLM gateway. See GET /models/ for what it serves.+ * @maxLength 128+ */+ model: string;+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields?: string[];+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputField[];+ /**+ * Number of the most recently archived, distinct orgs to classify (1-10). Each sampled org costs one LLM call, so keep this bounded during iteration.+ * @minimum 1+ * @maximum 10+ */+ sample?: number;+ }+export interface RunWidgetsResponse {/** Per-tile widget run results. */results: DashboardWidgetRunResult[];@@ -67613,6 +67739,33 @@ export namespace Schemas {task_id?: string;}+ export interface SaveRequest {+ /**+ * Label this config computes, e.g. ai_pilled.+ * @maxLength 128+ */+ label: string;+ /**+ * Version identity for the new row, e.g. v3. Optional: omit (or send blank) to accept the server-suggested next version for this label. Versions are immutable once created - there is no update endpoint - and (label, version) must be unique.+ * @maxLength 128+ */+ version?: string;+ /**+ * System prompt; {email} is replaced with the signup email domain at runtime. At most 20000 characters.+ * @maxLength 20000+ */+ prompt_text: string;+ /**+ * Gateway model to classify with, routed through the LLM gateway. See GET /models/ for what it serves.+ * @maxLength 128+ */+ model: string;+ /** Dotted paths into the archived Harmonic payload fed to the prompt, e.g. funding.fundingStage. Every selected value reaches the LLM and is then stored on the result indefinitely, so keep this list intentional. */+ input_fields?: string[];+ /** Output schema: list of {key, type, description}. type is 'boolean', 'number', or 'string'. This is the classifier's entire output contract - the label is a human name and is never an output key, so renaming a label changes nothing about what a version computes. Keys must match ^[a-z][a-z0-9_]*$, be unique, and not be 'meta' or 'inputs'. At most 20 fields. */+ output_fields: OutputField[];+ }+export interface SavedHeatmapListResponse {results: HeatmapScreenshotResponse[];/** Total number of saved heatmaps matching the filters. */@@ -79702,6 +79855,26 @@ export namespace Schemas {search: string;};+ export type GrowthAiEnrichmentConfigsRetrieveParams = {+ /**+ * Label name to list prompt config versions for.+ * @minLength 1+ */+ label: string;+ };++ export type GrowthAiEnrichmentRunCreateParams = {+ format?: GrowthAiEnrichmentRunCreateFormat;+ };++ export type GrowthAiEnrichmentRunCreateFormat = typeof GrowthAiEnrichmentRunCreateFormat[keyof typeof GrowthAiEnrichmentRunCreateFormat];+++ export const GrowthAiEnrichmentRunCreateFormat = {+ Json: 'json',+ Ndjson: 'ndjson',+ } as const;+export type LlmAnalyticsPersonalSpendListParams = {/*** When set, additionally return a `by_bucket` breakdown: a time-ascending UTC cost series for the scoped product at this bucket size in minutes, with per-bucket cost split into uncached input / output / cache read / cache creation components plus the matching token sums. Supported bucket sizes: 5, 15, 30, 60. The window may span at most 600 buckets of the chosen size (e.g. 50 hours at 5-minute buckets).