Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aeo): import prompt sets by api and rotate them by topic (#117873)

Lucas Ricoyf7248aecd6f7
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 2d1937f3210a..6a46c285b483 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -2704,6 +2704,16 @@
"table": null,
"type": "string"
},
+ "prompt_topic": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "prompt_topic",
+ "id": null,
+ "name": "prompt_topic",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"prompt_hash": {
"chain": null,
"fields": null,
@@ -16915,6 +16925,16 @@
"table": null,
"type": "string"
},
+ "prompt_topic": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "prompt_topic",
+ "id": null,
+ "name": "prompt_topic",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
"prompt_hash": {
"chain": null,
"fields": null,
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index afe498475c20..1a5582ca8d11 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -28,6 +28,7 @@ LIST_VIEWSETS_WITHOUT_DIRECT_SHARED_PAGINATION = {
}
EXISTING_CUSTOM_LIST_VIEWSETS = {
+ "products.aeo.backend.presentation.views.AEOPromptViewSet",
"ee.api.billing.BillingViewset",
"ee.api.quota_limits.QuotaLimitsViewSet",
"ee.api.subscription.SubscriptionDeliveryViewSet",
diff --git a/products/aeo/README.md b/products/aeo/README.md
index 57fce657523c..62acd35f08f7 100644
--- a/products/aeo/README.md
+++ b/products/aeo/README.md
@@ -27,8 +27,9 @@ The scheduled task is additionally gated per team by the `aeo-citation-tracking`
## Usage
```bash
-# 1. Seed the prompt set from a CSV (a `prompt` header column, or one prompt
-# per line). Use --csv-source manual for a hand-written set:
+# 1. Seed the prompt set from a CSV (a `prompt` header column with an optional
+# `topic` column, or one prompt per line). Use --csv-source manual for a
+# hand-written set:
python manage.py seed_aeo_prompts --team-id <id> --csv control_prompts.csv --csv-source manual
# 2. Smoke test — 3 prompts, real engine calls, nothing captured:
@@ -38,6 +39,24 @@ python manage.py run_aeo_citation_checks --team-id <id> --limit 3 --dry-run
python manage.py run_aeo_citation_checks --team-id <id>
```
+### Import over the API
+
+`/api/projects/<id>/aeo_prompts/` lists the prompt set, turns a prompt on or off (`PATCH {"active": false}`), and imports prompts with `POST bulk_import/`. It is gated by the `aeo-citation-tracking` flag and accepts personal API keys with `web_analytics:write`:
+
+```bash
+curl -X POST "$HOST/api/projects/<id>/aeo_prompts/bulk_import/" \
+ -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" -H "Content-Type: application/json" \
+ -d '{"prompts": [{"prompt": "Best open source session replay?", "topic": "Session replay", "external_visibility": 42}]}'
+```
+
+- A request takes up to 2,000 prompts. Send larger sets in batches of a few hundred.
+- A re-import matches prompts by normalized text. It updates the topic and the evidence, and keeps each prompt's on/off state.
+- `external_visibility` (0-100) is the share of answers that mention the brand, as reported by the tool the set came from. It is kept in the prompt's evidence to benchmark against our own rates.
+
+### Which prompts a run takes
+
+A run takes at most 50 prompts. It takes one prompt per topic in turn, so every topic is sampled on each run. Within a topic, prompts never checked come first, then the least recently checked, so a set larger than one run rotates.
+
## The table
`system.aeo_citation_checks` — one row per prompt × engine × run, read-only in HogQL:
@@ -45,6 +64,7 @@ python manage.py run_aeo_citation_checks --team-id <id>
| Column | Meaning |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `run_id`, `prompt_id`, `prompt_hash`, `prompt_text`, `prompt_source` | Which prompt, and whether it was `imported` from a CSV or written by hand (`manual`). |
+| `prompt_topic` | The prompt's topic when it ran; empty when it had none. Group by it to compare citation rates per topic. |
| `engine`, `model` | `claude-web-search`, `openai-web-search`, or `exa-answer`. |
| `cited` | Whether a target-domain URL appears in the answer's citations. |
| `cited_urls`, `target_urls`, `target_best_position`, `top_cited_domains` | The citation record. |
diff --git a/products/aeo/backend/facade/api.py b/products/aeo/backend/facade/api.py
index 6a22cabe30a6..24c95cb8f584 100644
--- a/products/aeo/backend/facade/api.py
+++ b/products/aeo/backend/facade/api.py
@@ -8,11 +8,22 @@ from __future__ import annotations
import datetime as dt
+from django.core.exceptions import ValidationError
+
from posthog.models.team import Team
from products.aeo.backend import gaps
-from products.aeo.backend.facade.contracts import CitationGap, CitationRunSummary
+from products.aeo.backend.facade.contracts import (
+ CitationGap,
+ CitationRunSummary,
+ Prompt,
+ PromptImport,
+ PromptImportResult,
+ PromptNotFoundError,
+)
+from products.aeo.backend.models import AEOPrompt
from products.aeo.backend.runner import run_citation_checks
+from products.aeo.backend.seeding import PromptCandidate, upsert_prompts
def run_citation_checks_for_team(team_id: int) -> CitationRunSummary:
@@ -25,3 +36,62 @@ def run_citation_checks_for_team(team_id: int) -> CitationRunSummary:
def list_citation_gaps(team_id: int, *, since: dt.datetime) -> list[CitationGap]:
return gaps.list_citation_gaps(team_id, since=since)
+
+
+def list_prompts(team_id: int, *, limit: int, offset: int) -> tuple[list[Prompt], int]:
+ """One page of the team's prompt set and the total count, paged in SQL."""
+ prompts = AEOPrompt.objects.for_team(team_id)
+ page = prompts.order_by("topic", "-rank", "created_at", "id")[offset : offset + limit]
+ return [_to_prompt(p) for p in page], prompts.count()
+
+
+def get_prompt(team_id: int, prompt_id: str) -> Prompt:
+ return _to_prompt(_get_prompt_row(team_id, prompt_id))
+
+
+def set_prompt_active(team_id: int, prompt_id: str, active: bool) -> Prompt:
+ prompt = _get_prompt_row(team_id, prompt_id)
+ prompt.active = active
+ prompt.save(update_fields=["active", "updated_at"])
+ return _to_prompt(prompt)
+
+
+def import_prompts(team_id: int, prompts: list[PromptImport]) -> PromptImportResult:
+ """Add prompts to the team's set, or update the topic and evidence of
+ prompts that already exist. Existing prompts keep their active state."""
+ team = Team.objects.get(id=team_id)
+ candidates = [
+ PromptCandidate(
+ text=item.prompt,
+ source=AEOPrompt.Source.IMPORTED,
+ topic=item.topic,
+ evidence={"via": "api"}
+ | ({"external_visibility": item.external_visibility} if item.external_visibility is not None else {}),
+ )
+ for item in prompts
+ ]
+ result = upsert_prompts(team, candidates)
+ return PromptImportResult(created=result["created"], updated=result["updated"], skipped=result["skipped"])
+
+
+def _get_prompt_row(team_id: int, prompt_id: str) -> AEOPrompt:
+ try:
+ return AEOPrompt.objects.for_team(team_id).get(id=prompt_id)
+ except (AEOPrompt.DoesNotExist, ValueError, ValidationError) as error:
+ raise PromptNotFoundError(prompt_id) from error
+
+
+def _to_prompt(prompt: AEOPrompt) -> Prompt:
+ visibility = (prompt.evidence or {}).get("external_visibility")
+ return Prompt(
+ id=str(prompt.id),
+ prompt=prompt.prompt,
+ topic=prompt.topic,
+ prompt_source=prompt.prompt_source,
+ rank=prompt.rank,
+ active=prompt.active,
+ last_checked_at=prompt.last_checked_at,
+ external_visibility=float(visibility) if isinstance(visibility, int | float) else None,
+ created_at=prompt.created_at,
+ updated_at=prompt.updated_at,
+ )
diff --git a/products/aeo/backend/facade/contracts.py b/products/aeo/backend/facade/contracts.py
index e683a198ca91..142c33c7dcb9 100644
--- a/products/aeo/backend/facade/contracts.py
+++ b/products/aeo/backend/facade/contracts.py
@@ -53,3 +53,39 @@ class CitationGap:
@property
def citation_rate(self) -> float:
return self.cited_checks / self.checks if self.checks else 0.0
+
+
+AEO_CITATION_TRACKING_FLAG = "aeo-citation-tracking"
+PROMPT_TOPIC_MAX_LENGTH = 200
+
+
+@frozen
+class Prompt:
+ id: str
+ prompt: str
+ topic: str
+ prompt_source: str
+ rank: float
+ active: bool
+ last_checked_at: dt.datetime | None
+ external_visibility: float | None
+ created_at: dt.datetime
+ updated_at: dt.datetime | None
+
+
+@frozen
+class PromptImport:
+ prompt: str
+ topic: str = ""
+ external_visibility: float | None = None
+
+
+@frozen
+class PromptImportResult:
+ created: int
+ updated: int
+ skipped: int
+
+
+class PromptNotFoundError(Exception):
+ pass
diff --git a/products/aeo/backend/facade/hogql.py b/products/aeo/backend/facade/hogql.py
index d10aaaf3aaaa..fdb4a21d10c5 100644
--- a/products/aeo/backend/facade/hogql.py
+++ b/products/aeo/backend/facade/hogql.py
@@ -38,6 +38,9 @@ aeo_citation_checks: PostgresTable = PostgresTable(
"prompt_source": StringDatabaseField(
name="prompt_source", description="Where the prompt came from: 'imported' or 'manual'."
),
+ "prompt_topic": StringDatabaseField(
+ name="prompt_topic", description="Topic the prompt belonged to when it ran; empty when it had none."
+ ),
"prompt_hash": StringDatabaseField(
name="prompt_hash", description="SHA-256 of the normalized prompt; stable join key across runs."
),
diff --git a/products/aeo/backend/migrations/0004_prompt_topic_and_rotation.py b/products/aeo/backend/migrations/0004_prompt_topic_and_rotation.py
new file mode 100644
index 000000000000..351cac25ebef
--- /dev/null
+++ b/products/aeo/backend/migrations/0004_prompt_topic_and_rotation.py
@@ -0,0 +1,48 @@
+# Generated by Django 5.2.18 on 2026-10-14 23:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("aeo", "0003_aeocitationcheck_answer_text"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="aeocitationcheck",
+ name="prompt_topic",
+ field=models.CharField(
+ blank=True,
+ db_default="",
+ default="",
+ help_text="Prompt topic at the time of the run.",
+ max_length=200,
+ ),
+ ),
+ migrations.AddField(
+ model_name="aeoprompt",
+ name="last_checked_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When the runner last ran this prompt; least recently checked runs first.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="aeoprompt",
+ name="topic",
+ field=models.CharField(
+ blank=True,
+ db_default="",
+ default="",
+ help_text="Theme the prompt belongs to; the runner samples every topic on each run.",
+ max_length=200,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="aeoprompt",
+ name="rank",
+ field=models.FloatField(default=0, help_text="Seeding score; higher runs first within a topic."),
+ ),
+ ]
diff --git a/products/aeo/backend/migrations/max_migration.txt b/products/aeo/backend/migrations/max_migration.txt
index c497e08610c8..f6fbe964fcdc 100644
--- a/products/aeo/backend/migrations/max_migration.txt
+++ b/products/aeo/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_aeocitationcheck_answer_text
+0004_prompt_topic_and_rotation
diff --git a/products/aeo/backend/models.py b/products/aeo/backend/models.py
index 984a513d6b83..27f6db14e95d 100644
--- a/products/aeo/backend/models.py
+++ b/products/aeo/backend/models.py
@@ -3,6 +3,8 @@ from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel
+from products.aeo.backend.facade.contracts import PROMPT_TOPIC_MAX_LENGTH
+
class AEOPrompt(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
"""
@@ -47,8 +49,18 @@ class AEOPrompt(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDT
blank=True,
help_text="Why this prompt made the set (for a CSV import, the file it came from).",
)
- rank = models.FloatField(default=0, help_text="Seeding score; higher runs first when the set is truncated.")
+ topic = models.CharField(
+ max_length=PROMPT_TOPIC_MAX_LENGTH,
+ blank=True,
+ default="",
+ db_default="",
+ help_text="Theme the prompt belongs to; the runner samples every topic on each run.",
+ )
+ rank = models.FloatField(default=0, help_text="Seeding score; higher runs first within a topic.")
active = models.BooleanField(default=True, help_text="Only active prompts are executed by the runner.")
+ last_checked_at = models.DateTimeField(
+ null=True, blank=True, help_text="When the runner last ran this prompt; least recently checked runs first."
+ )
class Meta:
db_table = "posthog_aeo_prompt"
@@ -88,6 +100,13 @@ class AEOCitationCheck(TeamScopedRootMixin, CreatedMetaFields, UUIDTModel):
run_id = models.UUIDField(help_text="Groups every check captured by one runner pass.")
prompt_text = models.TextField(help_text="The question as it ran, snapshotted from the prompt set.")
prompt_source = models.CharField(max_length=32, help_text="Prompt source at the time of the run.")
+ prompt_topic = models.CharField(
+ max_length=PROMPT_TOPIC_MAX_LENGTH,
+ blank=True,
+ default="",
+ db_default="",
+ help_text="Prompt topic at the time of the run.",
+ )
prompt_hash = models.CharField(max_length=64, help_text="SHA-256 of the normalized prompt text.")
engine = models.CharField(
diff --git a/products/aeo/backend/presentation/__init__.py b/products/aeo/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/aeo/backend/presentation/views.py b/products/aeo/backend/presentation/views.py
new file mode 100644
index 000000000000..7ed448ba4f94
--- /dev/null
+++ b/products/aeo/backend/presentation/views.py
@@ -0,0 +1,172 @@
+import math
+from typing import Any, cast
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.pagination import PrecountedLimitOffsetPagination
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.permissions import posthog_feature_flag_enabled
+
+from products.aeo.backend.facade.api import get_prompt, import_prompts, list_prompts, set_prompt_active
+from products.aeo.backend.facade.contracts import (
+ AEO_CITATION_TRACKING_FLAG,
+ PROMPT_TOPIC_MAX_LENGTH,
+ Prompt,
+ PromptImport,
+ PromptImportResult,
+ PromptNotFoundError,
+)
+
+MAX_PROMPTS_PER_IMPORT = 2000
+DEFAULT_PAGE_SIZE = 100
+# Bounds the request body. Prompts longer than the engines accept are counted as skipped, not rejected.
+MAX_IMPORTED_PROMPT_CHARS = 10_000
+
+EXTERNAL_VISIBILITY_HELP = (
+ "Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set "
+ "came from. Kept to benchmark against our own citation rate."
+)
+
+
+class AEOPromptSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = Prompt
+ ref_name = "AEOPrompt"
+ extra_kwargs = {
+ "id": {"help_text": "Prompt id."},
+ "prompt": {"help_text": "The question asked to the answer engines, as a user would phrase it."},
+ "topic": {"help_text": "Theme the prompt belongs to. The runner alternates between topics on each run."},
+ "prompt_source": {"help_text": "Where the prompt came from: 'imported' or 'manual'."},
+ "rank": {"help_text": "Seeding score. Within a topic, higher runs first."},
+ "active": {"help_text": "Only active prompts are run against the answer engines."},
+ "last_checked_at": {"help_text": "When the runner last ran this prompt. Null when it never ran."},
+ "external_visibility": {"help_text": EXTERNAL_VISIBILITY_HELP + " Null when the import carried none."},
+ "created_at": {"help_text": "When the prompt was added."},
+ "updated_at": {"help_text": "When the prompt last changed."},
+ }
+
+
+class AEOPromptUpdateRequestSerializer(serializers.Serializer):
+ active = serializers.BooleanField(help_text="Turn the prompt on or off for future runs.")
+
+
+class AEOPromptImportItemSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PromptImport
+ ref_name = "AEOPromptImport"
+ extra_kwargs = {
+ "prompt": {
+ "allow_blank": True,
+ "max_length": MAX_IMPORTED_PROMPT_CHARS,
+ "help_text": "The question to ask the answer engines, as a user would phrase it. Matching ignores case and whitespace, so a re-import updates the existing prompt.",
+ },
+ "topic": {
+ "max_length": PROMPT_TOPIC_MAX_LENGTH,
+ "allow_blank": True,
+ "help_text": "Theme the prompt belongs to. The runner alternates between topics on each run.",
+ },
+ "external_visibility": {"min_value": 0, "max_value": 100, "help_text": EXTERNAL_VISIBILITY_HELP},
+ }
+
+ def validate_external_visibility(self, value: float | None) -> float | None:
+ # DRF parses "NaN" and "Infinity" as floats, and NaN passes both bounds checks.
+ if value is not None and not math.isfinite(value):
+ raise serializers.ValidationError("Must be a finite number between 0 and 100.")
+ return value
+
+
+class AEOPromptBulkImportRequestSerializer(serializers.Serializer):
+ prompts = serializers.ListField(
+ child=AEOPromptImportItemSerializer(),
+ min_length=1,
+ max_length=MAX_PROMPTS_PER_IMPORT,
+ help_text=f"Prompts to add or update, at most {MAX_PROMPTS_PER_IMPORT} per request.",
+ )
+
+
+class AEOPromptImportResultSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PromptImportResult
+ ref_name = "AEOPromptImportResult"
+ extra_kwargs = {
+ "created": {"help_text": "Prompts added to the set."},
+ "updated": {"help_text": "Existing prompts that were updated. They keep their active state."},
+ "skipped": {"help_text": "Prompts that were empty or too long for the answer engines."},
+ }
+
+
+class AEOPromptViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "web_analytics"
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions = ["partial_update", "bulk_import"]
+ pagination_class = PrecountedLimitOffsetPagination
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ distinct_id = getattr(request.user, "distinct_id", None)
+ if not distinct_id or not posthog_feature_flag_enabled(
+ AEO_CITATION_TRACKING_FLAG, distinct_id, organization_id=self.organization_id
+ ):
+ raise PermissionDenied("This feature is not available.")
+
+ @extend_schema(
+ operation_id="aeo_prompts_list",
+ summary="List AEO prompts",
+ description="Lists the project's AEO prompt set, grouped by topic, one page at a time.",
+ responses={200: AEOPromptSerializer(many=True)},
+ tags=["web_analytics"],
+ )
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ paginator = cast(PrecountedLimitOffsetPagination, self.paginator)
+ prompts, count = list_prompts(
+ self.team_id, limit=paginator.get_limit(request) or DEFAULT_PAGE_SIZE, offset=paginator.get_offset(request)
+ )
+ paginator.set_count(count)
+ page = self.paginate_queryset(prompts)
+ return self.get_paginated_response(AEOPromptSerializer(page, many=True).data)
+
+ @validated_request(
+ operation_id="aeo_prompts_retrieve",
+ summary="Get an AEO prompt",
+ responses={200: OpenApiResponse(response=AEOPromptSerializer)},
+ tags=["web_analytics"],
+ )
+ def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ try:
+ return Response(AEOPromptSerializer(get_prompt(self.team_id, pk)).data)
+ except PromptNotFoundError:
+ raise NotFound()
+
+ @validated_request(
+ request_serializer=AEOPromptUpdateRequestSerializer,
+ operation_id="aeo_prompts_partial_update",
+ summary="Turn an AEO prompt on or off",
+ responses={200: OpenApiResponse(response=AEOPromptSerializer)},
+ tags=["web_analytics"],
+ )
+ def partial_update(self, request: ValidatedRequest, pk: str, **kwargs: Any) -> Response:
+ try:
+ prompt = set_prompt_active(self.team_id, pk, request.validated_data["active"])
+ except PromptNotFoundError:
+ raise NotFound()
+ return Response(AEOPromptSerializer(prompt).data)
+
+ @validated_request(
+ request_serializer=AEOPromptBulkImportRequestSerializer,
+ operation_id="aeo_prompts_bulk_import",
+ summary="Import AEO prompts",
+ description="Adds prompts to the project's AEO prompt set, or updates the topic and visibility of prompts that already exist. Existing prompts keep their active state.",
+ responses={200: OpenApiResponse(response=AEOPromptImportResultSerializer)},
+ tags=["web_analytics"],
+ )
+ @action(detail=False, methods=["post"])
+ def bulk_import(self, request: ValidatedRequest, **kwargs: Any) -> Response:
+ result = import_prompts(self.team_id, request.validated_data["prompts"])
+ return Response(AEOPromptImportResultSerializer(result).data)
diff --git a/products/aeo/backend/routes.py b/products/aeo/backend/routes.py
new file mode 100644
index 000000000000..bd5f1659d303
--- /dev/null
+++ b/products/aeo/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+from products.aeo.backend.presentation.views import AEOPromptViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"aeo_prompts", AEOPromptViewSet, "project_aeo_prompts", ["team_id"])
diff --git a/products/aeo/backend/runner.py b/products/aeo/backend/runner.py
index 6704ffcd9f22..8cb263b385eb 100644
--- a/products/aeo/backend/runner.py
+++ b/products/aeo/backend/runner.py
@@ -18,9 +18,13 @@ import uuid
from typing import Any, Optional
from django.conf import settings
+from django.db.models import F, Window
+from django.db.models.functions import RowNumber
+from django.utils import timezone
import structlog
+from posthog.models.scoping import team_scope
from posthog.models.team import Team
from products.aeo.backend.engines import CitationEngine, available_engines, build_check_fields
@@ -50,16 +54,14 @@ def run_citation_checks(
logger.warning("aeo_citation_run_no_engines", team_id=team.id)
return _empty_summary(team, "no engines configured (AI_GATEWAY_URL/AI_GATEWAY_API_KEY, EXA_API_KEY)"), []
- prompts = list(
- AEOPrompt.objects.for_team(team.id)
- .filter(active=True)
- .order_by("-rank", "created_at")[: DEFAULT_MAX_PROMPTS_PER_RUN if limit is None else limit]
- )
+ prompts = select_prompts(team, DEFAULT_MAX_PROMPTS_PER_RUN if limit is None else limit)
if not prompts:
logger.warning("aeo_citation_run_no_prompts", team_id=team.id)
return _empty_summary(team, "no active prompts — run `seed_aeo_prompts` first"), []
run_id = str(uuid.uuid4())
+ # bulk_create skips RootTeamMixin.save(), so map a child environment to its parent here, as reads do.
+ canonical_team_id = team.parent_team_id or team.id
target_domains: list[str] = settings.AEO_TARGET_DOMAINS
checks: list[dict[str, Any]] = []
engine_failures = 0
@@ -91,23 +93,30 @@ def run_citation_checks(
prompt_id=str(prompt.id),
error=check.error,
)
- fields = build_check_fields(
- check=check,
- run_id=run_id,
- prompt_id=str(prompt.id),
- prompt_text=prompt.prompt,
- prompt_source=prompt.prompt_source,
- prompt_hash=prompt.prompt_hash,
- target_domains=target_domains,
- )
- prompt_rows.append(AEOCitationCheck(team=team, **fields))
+ fields = {
+ **build_check_fields(
+ check=check,
+ run_id=run_id,
+ prompt_id=str(prompt.id),
+ prompt_text=prompt.prompt,
+ prompt_source=prompt.prompt_source,
+ prompt_hash=prompt.prompt_hash,
+ target_domains=target_domains,
+ ),
+ "prompt_topic": prompt.topic,
+ }
+ prompt_rows.append(AEOCitationCheck(team_id=canonical_team_id, **fields))
checks.append(fields)
if record and prompt_rows:
# Write per prompt so a mid-run crash keeps the completed checks.
try:
- AEOCitationCheck.objects.bulk_create(prompt_rows)
+ # The fail-closed manager refuses writes without a team scope, and none of the callers
+ # (the Celery task, the management command) run inside one.
+ with team_scope(canonical_team_id):
+ AEOCitationCheck.objects.bulk_create(prompt_rows)
rows_written += len(prompt_rows)
+ AEOPrompt.objects.for_team(team.id).filter(id=prompt.id).update(last_checked_at=timezone.now())
except Exception as e:
write_failures += len(prompt_rows)
logger.exception("aeo_citation_write_failed", team_id=team.id, run_id=run_id, error=str(e)[:300])
@@ -137,6 +146,36 @@ def run_citation_checks(
return summary, checks
+def select_prompts(team: Team, limit: int) -> list[AEOPrompt]:
+ """Pick up to `limit` active prompts, alternating between topics.
+
+ Each run samples every topic: it takes one prompt per topic in turn, so a
+ single large topic cannot fill the run. Within a topic, prompts never checked
+ come first, then the least recently checked, so a set larger than one run
+ rotates. A small topic runs out of unchecked prompts first and is then
+ re-checked while larger topics still rotate.
+ """
+ freshness = [F("last_checked_at").asc(nulls_first=True), F("rank").desc(), F("created_at").asc()]
+ by_topic: dict[str, list[AEOPrompt]] = {}
+ # The round-robin never takes more than `limit` prompts from one topic, so load no more than that.
+ for prompt in (
+ AEOPrompt.objects.for_team(team.id)
+ .filter(active=True)
+ .annotate(position_in_topic=Window(RowNumber(), partition_by=[F("topic")], order_by=freshness))
+ .filter(position_in_topic__lte=limit)
+ .order_by(*freshness)
+ ):
+ by_topic.setdefault(prompt.topic, []).append(prompt)
+
+ selected: list[AEOPrompt] = []
+ queues = list(by_topic.values())
+ position = 0
+ while len(selected) < limit and any(position < len(queue) for queue in queues):
+ selected.extend(queue[position] for queue in queues if position < len(queue))
+ position += 1
+ return selected[:limit]
+
+
def _empty_summary(team: Team, error: str) -> CitationRunSummary:
return CitationRunSummary(
team_id=team.id,
diff --git a/products/aeo/backend/seeding.py b/products/aeo/backend/seeding.py
index d7efb4a6357e..1aa2abf083f9 100644
--- a/products/aeo/backend/seeding.py
+++ b/products/aeo/backend/seeding.py
@@ -18,12 +18,16 @@ import hashlib
from dataclasses import field
from typing import Any
+from django.utils import timezone
+
import structlog
from posthog.dataclasses import frozen
+from posthog.models.scoping import team_scope
from posthog.models.team import Team
from products.aeo.backend.engines import MAX_PROMPT_LENGTH
+from products.aeo.backend.facade.contracts import PROMPT_TOPIC_MAX_LENGTH
from products.aeo.backend.models import AEOPrompt
logger = structlog.get_logger(__name__)
@@ -33,6 +37,7 @@ logger = structlog.get_logger(__name__)
class PromptCandidate:
text: str
source: str
+ topic: str = ""
rank: float = 0
evidence: dict[str, Any] = field(default_factory=dict)
@@ -46,24 +51,24 @@ def prompt_hash(text: str) -> str:
def import_prompts_csv(path: str, *, source: str = AEOPrompt.Source.IMPORTED) -> list[PromptCandidate]:
- """Import prompts from a CSV — either a file with a `prompt` header column,
- or a headerless file with one prompt per line."""
+ """Import prompts from a CSV — either a file with a `prompt` header column
+ (and an optional `topic` column), or a headerless file with one prompt per line."""
with open(path, newline="") as f:
first_row = next(csv.reader(f), None)
f.seek(0)
has_header = first_row is not None and any(cell.strip().lower() == "prompt" for cell in first_row)
- texts: list[str] = []
+ rows: list[tuple[str, str]] = []
if has_header:
for row in csv.DictReader(f):
- text = next((value for key, value in row.items() if key and key.strip().lower() == "prompt"), None)
- if text and text.strip():
- texts.append(text.strip())
+ cells = {key.strip().lower(): (value or "").strip() for key, value in row.items() if key}
+ if cells.get("prompt"):
+ rows.append((cells["prompt"], cells.get("topic", "")))
else:
for line in f:
text = line.strip().strip('"')
if text:
- texts.append(text)
- return [PromptCandidate(text=text, source=source, evidence={"file": path}) for text in texts]
+ rows.append((text, ""))
+ return [PromptCandidate(text=text, source=source, topic=topic, evidence={"file": path}) for text, topic in rows]
def upsert_prompts(team: Team, candidates: list[PromptCandidate]) -> dict[str, int]:
@@ -73,27 +78,41 @@ def upsert_prompts(team: Team, candidates: list[PromptCandidate]) -> dict[str, i
single prompt from bloating every check event it appears on, and it matches
what a check event records for prompt_text.
"""
- created = updated = skipped = 0
+ # bulk_create skips RootTeamMixin.save(), so map a child environment to its parent here, as reads do.
+ team_id = team.parent_team_id or team.id
+ skipped = 0
+ rows: dict[str, AEOPrompt] = {}
+ now = timezone.now()
for candidate in candidates:
text = normalize_prompt(candidate.text)
if not text or len(text) > MAX_PROMPT_LENGTH:
skipped += 1
continue
- # for_team scopes the fail-closed manager; team is still passed
- # explicitly because queryset filters don't propagate into row creation.
- _, was_created = AEOPrompt.objects.for_team(team.id).update_or_create(
- team=team,
- prompt_hash=prompt_hash(text),
- defaults={
- "prompt": text,
- "prompt_source": candidate.source,
- "rank": candidate.rank,
- "evidence": candidate.evidence,
- "active": True,
- },
+ key = prompt_hash(text)
+ # Keyed by hash because one upsert statement cannot touch the same row twice; the later copy wins.
+ rows[key] = AEOPrompt(
+ team_id=team_id,
+ prompt=text,
+ prompt_hash=key,
+ prompt_source=candidate.source,
+ topic=normalize_prompt(candidate.topic)[:PROMPT_TOPIC_MAX_LENGTH],
+ rank=candidate.rank,
+ evidence=candidate.evidence,
+ active=True,
+ updated_at=now,
+ )
+ valid = len(candidates) - skipped
+ with team_scope(team_id):
+ existing = set(AEOPrompt.objects.filter(prompt_hash__in=rows.keys()).values_list("prompt_hash", flat=True))
+ # `active` is left out of the update, so a re-import keeps prompts someone turned off.
+ # Sorted so concurrent imports lock conflicting rows in the same order and cannot deadlock.
+ AEOPrompt.objects.bulk_create(
+ [rows[key] for key in sorted(rows)],
+ update_conflicts=True,
+ unique_fields=["team", "prompt_hash"],
+ update_fields=["prompt", "prompt_source", "topic", "rank", "evidence", "updated_at"],
)
- created += was_created
- updated += not was_created
+ created = len(rows.keys() - existing)
if skipped:
logger.info("aeo_seed_candidates_skipped", team_id=team.id, skipped=skipped)
- return {"created": created, "updated": updated, "skipped": skipped}
+ return {"created": created, "updated": valid - created, "skipped": skipped}
diff --git a/products/aeo/backend/tasks/tasks.py b/products/aeo/backend/tasks/tasks.py
index fcde3e3ef992..1f2a69198528 100644
--- a/products/aeo/backend/tasks/tasks.py
+++ b/products/aeo/backend/tasks/tasks.py
@@ -19,11 +19,11 @@ from posthog.models.team import Team
from posthog.ph_client import feature_enabled_or_false
from posthog.scoping_audit import skip_team_scope_audit
+from products.aeo.backend.facade.contracts import AEO_CITATION_TRACKING_FLAG
from products.aeo.backend.runner import run_citation_checks
logger = structlog.get_logger(__name__)
-AEO_CITATION_TRACKING_FLAG = "aeo-citation-tracking"
# A full run is up to 50 prompts x 3 engines of sequential web-search calls
# (typically 10-60s each); four hours gives slow days headroom without letting
diff --git a/products/aeo/backend/test/test_api.py b/products/aeo/backend/test/test_api.py
new file mode 100644
index 000000000000..0539dfb19abc
--- /dev/null
+++ b/products/aeo/backend/test/test_api.py
@@ -0,0 +1,103 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
+from products.aeo.backend.models import AEOPrompt
+
+
+class TestAEOPromptAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag_patcher = patch(
+ "products.aeo.backend.presentation.views.posthog_feature_flag_enabled",
+ return_value=True,
+ )
+ self.feature_enabled = flag_patcher.start()
+ self.addCleanup(flag_patcher.stop)
+ self.url = f"/api/projects/{self.team.id}/aeo_prompts/"
+
+ def test_requires_the_rollout_flag(self) -> None:
+ self.feature_enabled.return_value = False
+
+ assert self.client.get(self.url).status_code == status.HTTP_403_FORBIDDEN
+ response = self.client.post(f"{self.url}bulk_import/", {"prompts": [{"prompt": "q?"}]}, format="json")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not AEOPrompt.objects.for_team(self.team.id).exists()
+
+ def test_bulk_import_then_deactivate_survives_a_reimport(self) -> None:
+ payload = {
+ "prompts": [
+ {"prompt": "Best session replay tool?", "topic": "Session replay", "external_visibility": 42.5},
+ {"prompt": "Best feature flag tool?", "topic": "Feature flags"},
+ {"prompt": " "},
+ ]
+ }
+ response = self.client.post(f"{self.url}bulk_import/", payload, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"created": 2, "updated": 0, "skipped": 1}
+
+ listed = {row["prompt"]: row for row in self.client.get(self.url).json()["results"]}
+ assert listed["Best session replay tool?"]["topic"] == "Session replay"
+ assert listed["Best session replay tool?"]["external_visibility"] == 42.5
+ assert listed["Best feature flag tool?"]["external_visibility"] is None
+
+ replay_id = listed["Best session replay tool?"]["id"]
+ response = self.client.patch(f"{self.url}{replay_id}/", {"active": False, "topic": "ignored"}, format="json")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["active"] is False
+ assert response.json()["topic"] == "Session replay"
+
+ response = self.client.post(f"{self.url}bulk_import/", payload, format="json")
+ assert response.json() == {"created": 0, "updated": 2, "skipped": 1}
+ assert AEOPrompt.objects.for_team(self.team.id).get(id=replay_id).active is False
+
+ def test_list_pages_without_overlap(self) -> None:
+ prompts = [{"prompt": f"q{i}?", "topic": "same topic"} for i in range(5)]
+ self.client.post(f"{self.url}bulk_import/", {"prompts": prompts}, format="json")
+
+ first = self.client.get(f"{self.url}?limit=3").json()
+ second = self.client.get(f"{self.url}?limit=3&offset=3").json()
+
+ assert first["count"] == 5
+ assert first["next"] is not None and second["next"] is None
+ ids = [row["id"] for row in first["results"] + second["results"]]
+ assert len(ids) == len(set(ids)) == 5
+
+ @parameterized.expand([("above_range", 140), ("not_a_number", "NaN"), ("infinite", "Infinity")])
+ def test_bulk_import_rejects_invalid_visibility(self, _name: str, visibility: object) -> None:
+ response = self.client.post(
+ f"{self.url}bulk_import/",
+ {"prompts": [{"prompt": "q?", "external_visibility": visibility}]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not AEOPrompt.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand(
+ [
+ ("write_scope", ["web_analytics:write"], status.HTTP_200_OK),
+ ("read_scope_only", ["web_analytics:read"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_bulk_import_with_a_personal_api_key(self, _name: str, scopes: list[str], expected: int) -> None:
+ # Session auth skips scope checks, so only a scoped key catches a custom action left out of the write actions.
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user, label="aeo import", secure_value=hash_key_value(value), scopes=scopes
+ )
+ self.client.logout()
+
+ response = self.client.post(
+ f"{self.url}bulk_import/",
+ {"prompts": [{"prompt": "Best session replay tool?"}]},
+ format="json",
+ headers={"authorization": f"Bearer {value}"},
+ )
+
+ assert response.status_code == expected, response.json()
diff --git a/products/aeo/backend/test/test_runner.py b/products/aeo/backend/test/test_runner.py
new file mode 100644
index 000000000000..8ee9d0726420
--- /dev/null
+++ b/products/aeo/backend/test/test_runner.py
@@ -0,0 +1,76 @@
+import datetime as dt
+
+import pytest
+
+from django.utils import timezone
+
+from posthog.models.organization import Organization
+from posthog.models.team import Team
+
+from products.aeo.backend.engines import CitationCheck
+from products.aeo.backend.models import AEOCitationCheck, AEOPrompt
+from products.aeo.backend.runner import run_citation_checks, select_prompts
+from products.aeo.backend.seeding import PromptCandidate, upsert_prompts
+
+
+def team(db: None) -> Team:
+ organization = Organization.objects.create(name="aeo test org")
+ return Team.objects.create(organization=organization, name="aeo test team")
+
+
+def test_select_prompts_alternates_topics_and_rotates_to_least_recently_checked(team: Team) -> None:
+ upsert_prompts(
+ team,
+ [
+ *(PromptCandidate(text=f"replay question {i}?", source="imported", topic="Replay") for i in range(5)),
+ PromptCandidate(text="flags question?", source="imported", topic="Flags"),
+ PromptCandidate(text="untagged question?", source="imported"),
+ ],
+ )
+ prompts = AEOPrompt.objects.for_team(team.id)
+ prompts.filter(prompt="replay question 0?").update(last_checked_at=timezone.now())
+ prompts.filter(prompt="flags question?").update(last_checked_at=timezone.now() - dt.timedelta(days=1))
+
+ selected = [p.prompt for p in select_prompts(team, limit=4)]
+
+ assert len(selected) == 4
+ assert {p.split(" question")[0] for p in selected} == {"replay", "flags", "untagged"}
+ assert "replay question 0?" not in selected
+
+
+def test_select_prompts_skips_inactive_prompts(team: Team) -> None:
+ upsert_prompts(team, [PromptCandidate(text=f"q{i}?", source="imported") for i in range(3)])
+ AEOPrompt.objects.for_team(team.id).filter(prompt="q1?").update(active=False)
+
+ assert sorted(p.prompt for p in select_prompts(team, limit=10)) == ["q0?", "q2?"]
+
+
+class _StubEngine:
+ name = "stub-engine"
+ model = "stub"
+
+ def run(self, prompt: str, *, trace_id: str, custom_properties: dict[str, str]) -> CitationCheck:
+ return CitationCheck(engine=self.name, model=self.model, cited_urls=["https://posthog.com/docs"])
+
+
[email protected]("via_child_environment", [False, True])
+def test_run_records_checks_and_rotates_without_a_team_scope(team: Team, settings, via_child_environment: bool) -> None:
+ settings.AEO_TARGET_DOMAINS = ["posthog.com"]
+ runner_team = (
+ Team.objects.create(organization=team.organization, name="child env", parent_team=team)
+ if via_child_environment
+ else team
+ )
+ upsert_prompts(
+ runner_team, [PromptCandidate(text=f"q{i}?", source="imported", topic=f"t{i % 2}") for i in range(4)]
+ )
+
+ first, _ = run_citation_checks(runner_team, engines=[_StubEngine()], limit=2)
+ second, _ = run_citation_checks(runner_team, engines=[_StubEngine()], limit=2)
+
+ assert (first.rows_written, second.rows_written) == (2, 2)
+ checks = AEOCitationCheck.objects.for_team(team.id)
+ assert checks.filter(cited=True).count() == 4
+ assert {c.prompt_topic for c in checks} == {"t0", "t1"}
+ assert len({c.prompt_id for c in checks}) == 4
diff --git a/products/aeo/backend/test/test_seeding.py b/products/aeo/backend/test/test_seeding.py
index ab6a72218ea7..dd67e739722b 100644
--- a/products/aeo/backend/test/test_seeding.py
+++ b/products/aeo/backend/test/test_seeding.py
@@ -31,13 +31,25 @@ def test_imports_csv_with_and_without_a_header(tmp_path: Path) -> None:
assert {c.source for c in candidates} == {AEOPrompt.Source.MANUAL}
+def test_imports_the_topic_column_when_present(tmp_path: Path) -> None:
+ path = tmp_path / "with_topic.csv"
+ path.write_text("Topic,Prompt\nSession replay,Best open source session replay?\n,Untagged question?\n")
+
+ candidates = import_prompts_csv(str(path))
+
+ assert [(c.text, c.topic) for c in candidates] == [
+ ("Best open source session replay?", "Session replay"),
+ ("Untagged question?", ""),
+ ]
+
+
def test_prompt_hash_ignores_case_and_whitespace() -> None:
assert prompt_hash(" Best Session Replay? ") == prompt_hash("best session replay?")
assert normalize_prompt(" Best Session Replay? ") == "Best Session Replay?"
-def _candidate(text: str) -> PromptCandidate:
- return PromptCandidate(text=text, source=AEOPrompt.Source.MANUAL)
+def _candidate(text: str, topic: str = "") -> PromptCandidate:
+ return PromptCandidate(text=text, source=AEOPrompt.Source.MANUAL, topic=topic)
@pytest.fixture
@@ -47,11 +59,16 @@ def team(db: None) -> Team:
def test_reseeding_the_same_prompt_updates_instead_of_duplicating(team: Team) -> None:
- assert upsert_prompts(team, [_candidate("Best session replay?")])["created"] == 1
- result = upsert_prompts(team, [_candidate(" best SESSION replay? ")])
+ first = upsert_prompts(team, [_candidate("Best session replay?"), _candidate("best session replay?")])
+ assert first == {"created": 1, "updated": 1, "skipped": 0}
+ AEOPrompt.objects.for_team(team.id).update(active=False)
+
+ result = upsert_prompts(team, [_candidate(" best SESSION replay? ", topic="Session replay")])
assert result == {"created": 0, "updated": 1, "skipped": 0}
- assert AEOPrompt.objects.for_team(team.id).count() == 1
+ prompt = AEOPrompt.objects.for_team(team.id).get()
+ assert prompt.topic == "Session replay"
+ assert prompt.active is False
def test_oversized_and_empty_prompts_are_skipped(team: Team) -> None:
@@ -68,3 +85,13 @@ def test_oversized_and_empty_prompts_are_skipped(team: Team) -> None:
assert result == {"created": 1, "updated": 0, "skipped": 2}
assert [p.prompt for p in AEOPrompt.objects.for_team(team.id)] == ["What is the best web analytics tool?"]
+
+
+def test_import_through_a_child_environment_lands_on_the_parent(team: Team) -> None:
+ child = Team.objects.create(organization=team.organization, name="child env", parent_team=team)
+ upsert_prompts(team, [_candidate("Best session replay?")])
+
+ result = upsert_prompts(child, [_candidate("best session replay?"), _candidate("Best feature flags?")])
+
+ assert result == {"created": 1, "updated": 1, "skipped": 0}
+ assert AEOPrompt.objects.for_team(team.id).count() == 2
diff --git a/products/aeo/turbo.json b/products/aeo/turbo.json
index 84d827f7c2e6..a38de87df10f 100644
--- a/products/aeo/turbo.json
+++ b/products/aeo/turbo.json
@@ -2,7 +2,14 @@
"extends": ["//"],
"tasks": {
"backend:contract-check": {
- "inputs": ["backend/facade/**", "backend/tasks/**", "backend/models.py", "backend/migrations/**"],
+ "inputs": [
+ "backend/facade/**",
+ "backend/tasks/**",
+ "backend/models.py",
+ "backend/migrations/**",
+ "backend/routes.py",
+ "backend/presentation/**"
+ ],
"outputs": [],
"cache": true
}
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index aa06e5a77da2..3b88492df61d 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,90 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface AEOPromptApi {
+ /** Prompt id. */
+ id: string
+ /** The question asked to the answer engines, as a user would phrase it. */
+ prompt: string
+ /** Theme the prompt belongs to. The runner alternates between topics on each run. */
+ topic: string
+ /** Where the prompt came from: 'imported' or 'manual'. */
+ prompt_source: string
+ /** Seeding score. Within a topic, higher runs first. */
+ rank: number
+ /** Only active prompts are run against the answer engines. */
+ active: boolean
+ /**
+ * When the runner last ran this prompt. Null when it never ran.
+ * @nullable
+ */
+ last_checked_at: string | null
+ /**
+ * Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set came from. Kept to benchmark against our own citation rate. Null when the import carried none.
+ * @nullable
+ */
+ external_visibility: number | null
+ /** When the prompt was added. */
+ created_at: string
+ /**
+ * When the prompt last changed.
+ * @nullable
+ */
+ updated_at: string | null
+}
+
+export interface PaginatedAEOPromptListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AEOPromptApi[]
+}
+
+export interface PatchedAEOPromptUpdateRequestApi {
+ /** Turn the prompt on or off for future runs. */
+ active?: boolean
+}
+
+export interface AEOPromptImportApi {
+ /**
+ * The question to ask the answer engines, as a user would phrase it. Matching ignores case and whitespace, so a re-import updates the existing prompt.
+ * @maxLength 10000
+ */
+ prompt: string
+ /**
+ * Theme the prompt belongs to. The runner alternates between topics on each run.
+ * @maxLength 200
+ */
+ topic?: string
+ /**
+ * Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set came from. Kept to benchmark against our own citation rate.
+ * @minimum 0
+ * @maximum 100
+ * @nullable
+ */
+ external_visibility?: number | null
+}
+
+export interface AEOPromptBulkImportRequestApi {
+ /**
+ * Prompts to add or update, at most 2000 per request.
+ * @minItems 1
+ * @maxItems 2000
+ */
+ prompts: AEOPromptImportApi[]
+}
+
+export interface AEOPromptImportResultApi {
+ /** Prompts added to the set. */
+ created: number
+ /** Existing prompts that were updated. They keep their active state. */
+ updated: number
+ /** Prompts that were empty or too long for the answer engines. */
+ skipped: number
+}
+
export interface HeatmapCapturePageApi {
/** A page URL that currently sends heatmap data. */
url: string
@@ -1639,6 +1723,17 @@ export interface GeneratePathCleaningSuggestionResponseApi {
suggestion?: PathCleaningSuggestionIssueApi | null
}
+export type AeoPromptsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type HeatmapScreenshotsContentRetrieveParams = {
/**
* Viewport width (CSS pixels) to fetch. Defaults to 1024. If no exact render exists for this width the closest available one is returned.
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index 17022d11ec61..61b8a913af43 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -9,9 +9,13 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ AEOPromptApi,
+ AEOPromptBulkImportRequestApi,
+ AEOPromptImportResultApi,
AchievementsListResponseApi,
AcknowledgeCelebrationRequestApi,
AcknowledgeCelebrationResponseApi,
+ AeoPromptsListParams,
ApplyPathCleaningSuggestionResponseApi,
ContentAutopilotExportResponseApi,
ContentAutopilotOpportunityApi,
@@ -42,11 +46,13 @@ import type {
HeatmapsResponseApi,
LlmsTxtFetchRequestApi,
LlmsTxtFetchResponseApi,
+ PaginatedAEOPromptListApi,
PaginatedContentAutopilotOpportunityListApi,
PaginatedContentAutopilotProposalListListApi,
PaginatedContentAutopilotRunListApi,
PaginatedContentAutopilotSiteProfileListApi,
PaginatedWebAnalyticsFilterPresetListApi,
+ PatchedAEOPromptUpdateRequestApi,
PatchedContentAutopilotSiteProfileApi,
PatchedHeatmapCaptureSettingsRequestApi,
PatchedHeatmapScreenshotSettingsRequestApi,
@@ -92,6 +98,97 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getAeoPromptsListUrl = (projectId: string, params?: AeoPromptsListParams) => {
+ 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/projects/${projectId}/aeo_prompts/?${stringifiedParams}`
+ : `/api/projects/${projectId}/aeo_prompts/`
+}
+
+/**
+ * Lists the project's AEO prompt set, grouped by topic, one page at a time.
+ * @summary List AEO prompts
+ */
+export const aeoPromptsList = async (
+ projectId: string,
+ params?: AeoPromptsListParams,
+ options?: RequestInit
+): Promise<PaginatedAEOPromptListApi> => {
+ return apiMutator<PaginatedAEOPromptListApi>(getAeoPromptsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAeoPromptsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/aeo_prompts/${id}/`
+}
+
+/**
+ * @summary Get an AEO prompt
+ */
+export const aeoPromptsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AEOPromptApi> => {
+ return apiMutator<AEOPromptApi>(getAeoPromptsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAeoPromptsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/aeo_prompts/${id}/`
+}
+
+/**
+ * @summary Turn an AEO prompt on or off
+ */
+export const aeoPromptsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedAEOPromptUpdateRequestApi?: PatchedAEOPromptUpdateRequestApi,
+ options?: RequestInit
+): Promise<AEOPromptApi> => {
+ return apiMutator<AEOPromptApi>(getAeoPromptsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedAEOPromptUpdateRequestApi),
+ })
+}
+
+export const getAeoPromptsBulkImportUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/aeo_prompts/bulk_import/`
+}
+
+/**
+ * Adds prompts to the project's AEO prompt set, or updates the topic and visibility of prompts that already exist. Existing prompts keep their active state.
+ * @summary Import AEO prompts
+ */
+export const aeoPromptsBulkImport = async (
+ projectId: string,
+ aEOPromptBulkImportRequestApi: AEOPromptBulkImportRequestApi,
+ options?: RequestInit
+): Promise<AEOPromptImportResultApi> => {
+ return apiMutator<AEOPromptImportResultApi>(getAeoPromptsBulkImportUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(aEOPromptBulkImportRequestApi),
+ })
+}
+
export const getHeatmapCapturePagesRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/heatmap_capture/pages/`
}
diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.ts
index 1a0b8efce84f..5354843cc06f 100644
--- a/products/web_analytics/frontend/generated/api.zod.ts
+++ b/products/web_analytics/frontend/generated/api.zod.ts
@@ -9,6 +9,56 @@
*/
import * as zod from 'zod'
+/**
+ * @summary Turn an AEO prompt on or off
+ */
+export const AeoPromptsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ active: zod.boolean().optional().describe('Turn the prompt on or off for future runs.'),
+})
+
+/**
+ * Adds prompts to the project's AEO prompt set, or updates the topic and visibility of prompts that already exist. Existing prompts keep their active state.
+ * @summary Import AEO prompts
+ */
+export const aeoPromptsBulkImportBodyPromptsItemPromptMax = 10000
+
+export const aeoPromptsBulkImportBodyPromptsItemTopicMax = 200
+
+export const aeoPromptsBulkImportBodyPromptsItemExternalVisibilityMin = 0
+export const aeoPromptsBulkImportBodyPromptsItemExternalVisibilityMax = 100
+
+export const aeoPromptsBulkImportBodyPromptsMax = 2000
+
+export const AeoPromptsBulkImportBody = /* @__PURE__ */ zod.object({
+ prompts: zod
+ .array(
+ zod.object({
+ prompt: zod
+ .string()
+ .max(aeoPromptsBulkImportBodyPromptsItemPromptMax)
+ .describe(
+ 'The question to ask the answer engines, as a user would phrase it. Matching ignores case and whitespace, so a re-import updates the existing prompt.'
+ ),
+ topic: zod
+ .string()
+ .max(aeoPromptsBulkImportBodyPromptsItemTopicMax)
+ .optional()
+ .describe('Theme the prompt belongs to. The runner alternates between topics on each run.'),
+ external_visibility: zod
+ .number()
+ .min(aeoPromptsBulkImportBodyPromptsItemExternalVisibilityMin)
+ .max(aeoPromptsBulkImportBodyPromptsItemExternalVisibilityMax)
+ .nullish()
+ .describe(
+ 'Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set came from. Kept to benchmark against our own citation rate.'
+ ),
+ })
+ )
+ .min(1)
+ .max(aeoPromptsBulkImportBodyPromptsMax)
+ .describe('Prompts to add or update, at most 2000 per request.'),
+})
+
export const heatmapCaptureSettingsUpdateBodyUrlAllowlistItemMax = 2000
export const heatmapCaptureSettingsUpdateBodyUrlAllowlistMax = 100
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5b0d6d34ce6d..a17756cf6f4c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13,6 +13,76 @@ export namespace Schemas {
/**
*
*/
+ export interface AEOPrompt {
+ /** Prompt id. */
+ id: string;
+ /** The question asked to the answer engines, as a user would phrase it. */
+ prompt: string;
+ /** Theme the prompt belongs to. The runner alternates between topics on each run. */
+ topic: string;
+ /** Where the prompt came from: 'imported' or 'manual'. */
+ prompt_source: string;
+ /** Seeding score. Within a topic, higher runs first. */
+ rank: number;
+ /** Only active prompts are run against the answer engines. */
+ active: boolean;
+ /**
+ * When the runner last ran this prompt. Null when it never ran.
+ * @nullable
+ */
+ last_checked_at: string | null;
+ /**
+ * Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set came from. Kept to benchmark against our own citation rate. Null when the import carried none.
+ * @nullable
+ */
+ external_visibility: number | null;
+ /** When the prompt was added. */
+ created_at: string;
+ /**
+ * When the prompt last changed.
+ * @nullable
+ */
+ updated_at: string | null;
+ }
+
+ export interface AEOPromptImport {
+ /**
+ * The question to ask the answer engines, as a user would phrase it. Matching ignores case and whitespace, so a re-import updates the existing prompt.
+ * @maxLength 10000
+ */
+ prompt: string;
+ /**
+ * Theme the prompt belongs to. The runner alternates between topics on each run.
+ * @maxLength 200
+ */
+ topic?: string;
+ /**
+ * Share of answers (0-100) that mention the brand for this prompt, as reported by the tool the prompt set came from. Kept to benchmark against our own citation rate.
+ * @minimum 0
+ * @maximum 100
+ * @nullable
+ */
+ external_visibility?: number | null;
+ }
+
+ export interface AEOPromptBulkImportRequest {
+ /**
+ * Prompts to add or update, at most 2000 per request.
+ * @minItems 1
+ * @maxItems 2000
+ */
+ prompts: AEOPromptImport[];
+ }
+
+ export interface AEOPromptImportResult {
+ /** Prompts added to the set. */
+ created: number;
+ /** Existing prompts that were updated. They keep their active state. */
+ updated: number;
+ /** Prompts that were empty or too long for the answer engines. */
+ skipped: number;
+ }
+
export interface AIContextAccountProperty {
/** Customer analytics account property definition id. */
id: string;
@@ -70154,6 +70224,15 @@ export namespace Schemas {
seconds_per_merged_pr: number;
}
+ export interface PaginatedAEOPromptList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AEOPrompt[];
+ }
+
export interface PaginatedAccountChannelSummaryList {
count: number;
/** @nullable */
@@ -78140,6 +78219,11 @@ export namespace Schemas {
success_rate: number | null;
}
+ export interface PatchedAEOPromptUpdateRequest {
+ /** Turn the prompt on or off for future runs. */
+ active?: boolean;
+ }
+
/**
* Typed account properties: website_domain, external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link, metabase_link), and touchpoint matching lists: email_domains (the company's email domains) and known_emails (individual addresses pinned to the account). Defaults to an empty object. Unknown keys are rejected. User assignments live on account relationships, not here.
* @nullable
@@ -119788,6 +119872,17 @@ export namespace Schemas {
Ocsf: 'ocsf',
} as const;
+ export type AeoPromptsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type AiObservabilityInstrumentationChecklistRetrieveParams = {
/**
* Grade the checks against a fresh read instead of a recent cached one. Use it after changing instrumentation, when a cached verdict would still describe the old code.