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(workflows): add an api for broadcast audience suggestions (#124199)

Daniel Marchukc534e25ed74c
diff --git a/products/workflows/backend/facade/audience_suggestions.py b/products/workflows/backend/facade/audience_suggestions.py
new file mode 100644
index 000000000000..37089f18beb7
--- /dev/null
+++ b/products/workflows/backend/facade/audience_suggestions.py
@@ -0,0 +1,33 @@
+"""Broadcast audiences written by AI from a project's own events."""
+
+from posthog.models import Team, User
+
+from products.workflows.backend.facade.contracts import AudienceSuggestionsResult
+from products.workflows.backend.services.audience_suggestions import service
+from products.workflows.backend.services.audience_suggestions.service import (
+ FEATURE_FLAG_KEY,
+ can_read_email,
+ get_audience_suggestion,
+ get_audience_suggestions,
+ is_enabled,
+ needs_new_generation,
+)
+from products.workflows.backend.tasks.audience_suggestions import generate_audience_suggestions
+
+__all__ = [
+ "FEATURE_FLAG_KEY",
+ "can_read_email",
+ "get_audience_suggestion",
+ "get_audience_suggestions",
+ "is_enabled",
+ "needs_new_generation",
+ "start_audience_suggestions",
+]
+
+
+def start_audience_suggestions(*, team: Team, user: User, refresh: bool) -> AudienceSuggestionsResult:
+ return service.start_audience_suggestions(
+ team=team,
+ refresh=refresh,
+ enqueue=lambda lock_token: generate_audience_suggestions.delay(team.id, user.id, lock_token),
+ )
diff --git a/products/workflows/backend/presentation/views/broadcast_audience_suggestions.py b/products/workflows/backend/presentation/views/broadcast_audience_suggestions.py
new file mode 100644
index 000000000000..aaaaefc1026b
--- /dev/null
+++ b/products/workflows/backend/presentation/views/broadcast_audience_suggestions.py
@@ -0,0 +1,124 @@
+from typing import Any
+
+from django.db import models
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models import User
+from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
+
+from products.workflows.backend.facade.audience_suggestions import (
+ can_read_email,
+ get_audience_suggestions,
+ is_enabled,
+ needs_new_generation,
+ start_audience_suggestions,
+)
+from products.workflows.backend.presentation.views.workflow_data_suggestions import (
+ DataSuggestionGenerateRequestSerializer,
+ DataSuggestionsStatus,
+)
+
+
+class AudienceSuggestionKind(models.TextChoices):
+ NOT_YET = "not_yet"
+ REGULARS = "regulars"
+ LAPSED = "lapsed"
+
+
+class AudienceSuggestionSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Opaque id of this suggestion, valid while the suggestions stay cached.")
+ name = serializers.CharField(help_text="Suggested audience name, written by AI from the project's events.")
+ description = serializers.CharField(
+ help_text="Who the people are and what to tell them. Used as the cohort description and the email brief."
+ )
+ reason = serializers.CharField(help_text="One sentence on why the audience is worth a broadcast.")
+ kind = serializers.ChoiceField(
+ choices=AudienceSuggestionKind.choices,
+ help_text="not_yet: did event in the window but not missing_event. regulars: did event at least min_count "
+ "times in the window. lapsed: did event in the last 90 days but not in the window.",
+ )
+ event = serializers.CharField(help_text="The project event the audience is built on.")
+ missing_event = serializers.CharField(
+ allow_null=True, help_text="For not_yet: the event the audience has not done yet. Null otherwise."
+ )
+ window_days = serializers.IntegerField(help_text="The time window in days.")
+ min_count = serializers.IntegerField(
+ allow_null=True, help_text="For regulars: how many times the event must happen in the window."
+ )
+ reachable_count = serializers.IntegerField(
+ help_text="People in the audience with an email address, counted when the suggestion was made."
+ )
+ cohort_filters = serializers.JSONField(
+ help_text="The audience's cohort filters, in the cohorts endpoint's `filters` format. Saved as a static cohort."
+ )
+
+
+class AudienceSuggestionsResponseSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=DataSuggestionsStatus.choices,
+ help_text="ready when suggestions were made (the list can still be empty), generating while a background "
+ "run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI "
+ "data processing, unavailable when nothing was made or the run failed.",
+ )
+ suggestions = AudienceSuggestionSerializer(many=True, help_text="Up to 3 suggested broadcast audiences.")
+
+
+class BroadcastAudienceSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """Broadcast audiences written by AI from the project's own events. Both calls are free for the customer."""
+
+ scope_object = "hog_flow"
+ requires_resource_level_access = True
+ scope_object_read_actions = ["current"]
+ scope_object_write_actions = ["generate"]
+
+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:
+ # The cards carry the project's event names and audience sizes, so a key also needs the scope that reads them.
+ access = "read" if self.action in self.scope_object_read_actions else "write"
+ return [f"hog_flow:{access}", "query:read"]
+
+ def get_throttles(self):
+ if self.action == "generate" and self._starts_generation():
+ return [AIBurstRateThrottle(), AISustainedRateThrottle()]
+ return super().get_throttles()
+
+ def _starts_generation(self) -> bool:
+ payload = DataSuggestionGenerateRequestSerializer(data=self.request.data)
+ return not payload.is_valid() or needs_new_generation(team=self.team, refresh=payload.validated_data["refresh"])
+
+ @extend_schema(
+ operation_id="broadcast_audience_suggestions_current", responses={200: AudienceSuggestionsResponseSerializer}
+ )
+ @action(detail=False, methods=["get"])
+ def current(self, request: Request, **kwargs: Any) -> Response:
+ self._user_with_feature(request)
+ return Response(AudienceSuggestionsResponseSerializer(get_audience_suggestions(team=self.team)).data)
+
+ @extend_schema(
+ operation_id="broadcast_audience_suggestions_generate",
+ request=DataSuggestionGenerateRequestSerializer,
+ responses={200: AudienceSuggestionsResponseSerializer},
+ )
+ @action(detail=False, methods=["post"])
+ def generate(self, request: Request, **kwargs: Any) -> Response:
+ user = self._user_with_feature(request)
+ payload = DataSuggestionGenerateRequestSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ result = start_audience_suggestions(team=self.team, user=user, refresh=payload.validated_data["refresh"])
+ return Response(AudienceSuggestionsResponseSerializer(result).data)
+
+ def _user_with_feature(self, request: Request) -> User:
+ user = request.user
+ if not isinstance(user, User) or not is_enabled(user, str(self.organization.id)):
+ raise PermissionDenied("This feature is not available.")
+ # The cards are shared by the whole project and count people by email, so they stay hidden from anyone
+ # whose access hides email addresses.
+ if not can_read_email(user, self.team.id):
+ raise PermissionDenied("Audience ideas need access to people's email addresses.")
+ return user
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index ebd9c987c400..ce23f8693d32 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -6,6 +6,7 @@ from posthog.ingress.views import build_webhook_view
from posthog.utils import opt_slash_path
from products.workflows.backend.presentation.views import (
+ broadcast_audience_suggestions,
email_drafts,
hog_flow,
hog_flow_template,
@@ -42,6 +43,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_data_suggestions",
["team_id"],
)
+ routers.projects.register(
+ r"broadcast_audience_suggestions",
+ broadcast_audience_suggestions.BroadcastAudienceSuggestionsViewSet,
+ "project_broadcast_audience_suggestions",
+ ["team_id"],
+ )
routers.projects.register(
r"workflow_sending_rules",
workflow_sending_rules.WorkflowSendingRulesViewSet,
diff --git a/products/workflows/backend/tests/api/test_broadcast_audience_suggestions.py b/products/workflows/backend/tests/api/test_broadcast_audience_suggestions.py
new file mode 100644
index 000000000000..1dc3ce29fcd9
--- /dev/null
+++ b/products/workflows/backend/tests/api/test_broadcast_audience_suggestions.py
@@ -0,0 +1,235 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.exceptions import ClickHouseQueryTimeOut
+from posthog.models import PropertyDefinition
+from posthog.test.persons import create_person
+
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
+from products.cohorts.backend.models.cohort import Cohort
+from products.workflows.backend.facade.contracts import AudienceKind
+from products.workflows.backend.services.audience_suggestions.audience import cohort_filters, reachable_count
+from products.workflows.backend.services.audience_suggestions.planner import AudienceIdea
+from products.workflows.backend.services.audience_suggestions.service import _cache_key
+
+SERVICE = "products.workflows.backend.services.audience_suggestions.service"
+FLAG = f"{SERVICE}.posthoganalytics.feature_enabled"
+
+
+def _idea(
+ kind: AudienceKind,
+ event: str,
+ missing_event: str | None = None,
+ window_days: int = 14,
+ min_count: int | None = None,
+) -> AudienceIdea:
+ return AudienceIdea(
+ name=f"People who did {event}",
+ description="People to tell about the next step.",
+ reason="They are worth a note.",
+ kind=kind,
+ event=event,
+ missing_event=missing_event,
+ window_days=window_days,
+ min_count=min_count,
+ )
+
+
+class TestBroadcastAudienceSuggestions(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.delete(_cache_key(self.team.id))
+ self.flag = patch(FLAG, return_value=True).start()
+ # FLAG patches the shared feature_enabled, which the privacy mode check reads too.
+ patch(f"{SERVICE}.is_privacy_mode_enabled", return_value=False).start()
+ self.addCleanup(patch.stopall)
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ now = datetime.now(UTC)
+ window_start = (now - timedelta(days=14)).replace(hour=0, minute=0, second=0, microsecond=0)
+ # 12 recent sign-ups without a project, one with a project, and two without a usable email address.
+ for index in range(12):
+ self._person(f"new-{index}", [("signed_up", now - timedelta(days=2))])
+ self._person(
+ "activated", [("signed_up", now - timedelta(days=2)), ("project_created", now - timedelta(days=1))]
+ )
+ self._person("no-email", [("signed_up", now - timedelta(days=2))], email=None)
+ self._person("empty-email", [("signed_up", now - timedelta(days=2))], email="")
+ # The window starts at the start of the day, like the cohort's relative dates.
+ self._person("first-day", [("signed_up", window_start + timedelta(hours=1))])
+ self._person("day-before", [("signed_up", window_start - timedelta(hours=1))])
+ # 11 regulars with 3 pageviews this week, and 11 people last seen 40 days ago.
+ for index in range(11):
+ self._person(f"regular-{index}", [("$pageview", now - timedelta(days=day)) for day in (1, 2, 3)])
+ self._person(f"lapsed-{index}", [("$pageview", now - timedelta(days=40))])
+ # A regulars window is rolling and ends now, so the third view of each reader falls outside it.
+ window_edge = now - timedelta(days=7)
+ edge_day_start = window_edge.replace(hour=0, minute=0, second=0, microsecond=0)
+ self._person("steady-reader", [("report_viewed", now - timedelta(days=day)) for day in (1, 2, 3)])
+ self._person(
+ "edge-reader",
+ [
+ ("report_viewed", now - timedelta(days=1)),
+ ("report_viewed", now - timedelta(days=2)),
+ ("report_viewed", edge_day_start + (window_edge - edge_day_start) / 2),
+ ],
+ )
+ self._person(
+ "future-reader",
+ [("report_viewed", now - timedelta(days=day)) for day in (1, 2)]
+ + [("report_viewed", now + timedelta(days=1))],
+ )
+ flush_persons_and_events()
+
+ def _person(self, distinct_id: str, events: list[tuple[str, datetime]], email: str | None = "set") -> None:
+ properties = {} if email is None else {"email": f"{distinct_id}@example.com" if email == "set" else email}
+ create_person(team=self.team, distinct_ids=[distinct_id], properties=properties)
+ for event, timestamp in events:
+ _create_event(team=self.team, event=event, distinct_id=distinct_id, timestamp=timestamp)
+
+ def _list(self) -> dict:
+ url = f"/api/projects/{self.team.id}/broadcast_audience_suggestions/"
+ # Celery runs eagerly in tests, so the run that generate starts has finished when it returns.
+ started = self.client.post(f"{url}generate/", {}, format="json")
+ assert started.status_code == 200, started.json()
+ response = self.client.get(f"{url}current/")
+ assert response.status_code == 200, response.json()
+ return response.json()
+
+ @parameterized.expand(
+ [
+ ("not_yet", "signed_up", "project_created", 14, None, 13),
+ ("regulars", "$pageview", None, 7, 3, 11),
+ ("regulars", "report_viewed", None, 7, 3, 1),
+ ("lapsed", "$pageview", None, 30, None, 11),
+ ]
+ )
+ def test_card_count_matches_the_calculated_cohort(
+ self,
+ kind: AudienceKind,
+ event: str,
+ missing_event: str | None,
+ window_days: int,
+ min_count: int | None,
+ expected: int,
+ ) -> None:
+ filters = cohort_filters(
+ kind=kind, event=event, missing_event=missing_event, window_days=window_days, min_count=min_count
+ )
+ cohort = Cohort.objects.create(team=self.team, name="Audience", filters=filters)
+ cohort.calculate_people_ch(pending_version=0)
+ cohort.refresh_from_db()
+
+ count = reachable_count(
+ self.team, kind=kind, event=event, missing_event=missing_event, window_days=window_days, min_count=min_count
+ )
+ assert count == expected
+ assert cohort.count == expected
+
+ @patch(f"{SERVICE}.suggest_audiences")
+ def test_keeps_valid_audiences_one_per_kind_and_caches_them(self, suggest: MagicMock) -> None:
+ suggest.return_value = [
+ _idea("not_yet", "signed_up", "project_created"),
+ _idea("not_yet", "made_up_event", "project_created"),
+ _idea("not_yet", "signed_up", "signed_up"),
+ # Fewer than 10 people with an email address.
+ _idea("regulars", "project_created", window_days=7, min_count=3),
+ _idea("lapsed", "$pageview", window_days=30),
+ _idea("not_yet", "$pageview", "project_created"),
+ ]
+
+ body = self._list()
+
+ assert body["status"] == "ready"
+ assert [(s["kind"], s["event"], s["reachable_count"]) for s in body["suggestions"]] == [
+ ("not_yet", "signed_up", 13),
+ ("lapsed", "$pageview", 11),
+ ("not_yet", "$pageview", 11),
+ ]
+ prompt_events = dict(suggest.call_args.kwargs["events"])
+ assert prompt_events["$pageview"] == 33
+ assert self._list()["suggestions"] == body["suggestions"]
+ assert suggest.call_count == 1
+
+ @patch(f"{SERVICE}.reachable_count")
+ @patch(f"{SERVICE}.suggest_audiences")
+ def test_an_audience_too_costly_to_count_drops_only_that_card(self, suggest: MagicMock, count: MagicMock) -> None:
+ suggest.return_value = [
+ _idea("lapsed", "$pageview", window_days=30),
+ _idea("not_yet", "signed_up", "project_created"),
+ ]
+
+ def size(team: object, *, kind: AudienceKind, **_: object) -> int:
+ if kind == "lapsed":
+ raise ClickHouseQueryTimeOut()
+ return 13
+
+ count.side_effect = size
+
+ body = self._list()
+
+ assert body["status"] == "ready"
+ assert [(s["kind"], s["reachable_count"]) for s in body["suggestions"]] == [("not_yet", 13)]
+
+ @patch(f"{SERVICE}.activity_counts", side_effect=ClickHouseQueryTimeOut())
+ @patch(f"{SERVICE}.suggest_audiences")
+ def test_a_failed_activity_count_still_suggests_audiences_from_project_events(
+ self, suggest: MagicMock, _activity: MagicMock
+ ) -> None:
+ suggest.return_value = [
+ _idea("lapsed", "$pageview", window_days=30),
+ _idea("not_yet", "signed_up", "project_created"),
+ ]
+
+ body = self._list()
+
+ assert body["status"] == "ready"
+ assert [(s["kind"], s["event"]) for s in body["suggestions"]] == [("not_yet", "signed_up")]
+ assert "$pageview" not in dict(suggest.call_args.kwargs["events"])
+
+ @parameterized.expand(
+ [
+ ("ai_not_approved", False, True, False, 200, "ai_not_approved"),
+ ("flag_off", True, False, False, 403, None),
+ ("email_hidden_from_the_user", True, True, True, 403, None),
+ ]
+ )
+ @patch(f"{SERVICE}.suggest_audiences")
+ def test_runs_nothing_without_consent_or_flag(
+ self,
+ _name: str,
+ approved: bool,
+ flag_on: bool,
+ email_restricted: bool,
+ status_code: int,
+ status: str | None,
+ suggest: MagicMock,
+ ) -> None:
+ self.flag.return_value = flag_on
+ self.organization.is_ai_data_processing_approved = approved
+ if email_restricted:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ email = PropertyDefinition.objects.create(
+ team=self.team, name="email", property_type="String", type=PropertyDefinition.Type.PERSON
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=email, access_level=PropertyAccessLevel.NONE.value
+ )
+ self.organization.save()
+
+ response = self.client.post(f"/api/projects/{self.team.id}/broadcast_audience_suggestions/generate/", {})
+
+ assert response.status_code == status_code
+ if status:
+ assert response.json()["status"] == status
+ suggest.assert_not_called()
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index fdf9163bec64..efe1c45a3231 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -7,6 +7,88 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `ready` - Ready
+ * * `generating` - Generating
+ * * `ai_not_approved` - Ai Not Approved
+ * * `unavailable` - Unavailable
+ */
+export type DataSuggestionsStatusEnumApi =
+ (typeof DataSuggestionsStatusEnumApi)[keyof typeof DataSuggestionsStatusEnumApi]
+
+export const DataSuggestionsStatusEnumApi = {
+ Ready: 'ready',
+ Generating: 'generating',
+ AiNotApproved: 'ai_not_approved',
+ Unavailable: 'unavailable',
+} as const
+
+/**
+ * * `not_yet` - Not Yet
+ * * `regulars` - Regulars
+ * * `lapsed` - Lapsed
+ */
+export type AudienceSuggestionKindEnumApi =
+ (typeof AudienceSuggestionKindEnumApi)[keyof typeof AudienceSuggestionKindEnumApi]
+
+export const AudienceSuggestionKindEnumApi = {
+ NotYet: 'not_yet',
+ Regulars: 'regulars',
+ Lapsed: 'lapsed',
+} as const
+
+export interface AudienceSuggestionApi {
+ /** Opaque id of this suggestion, valid while the suggestions stay cached. */
+ id: string
+ /** Suggested audience name, written by AI from the project's events. */
+ name: string
+ /** Who the people are and what to tell them. Used as the cohort description and the email brief. */
+ description: string
+ /** One sentence on why the audience is worth a broadcast. */
+ reason: string
+ /** not_yet: did event in the window but not missing_event. regulars: did event at least min_count times in the window. lapsed: did event in the last 90 days but not in the window.
+ *
+ * * `not_yet` - Not Yet
+ * * `regulars` - Regulars
+ * * `lapsed` - Lapsed */
+ kind: AudienceSuggestionKindEnumApi
+ /** The project event the audience is built on. */
+ event: string
+ /**
+ * For not_yet: the event the audience has not done yet. Null otherwise.
+ * @nullable
+ */
+ missing_event: string | null
+ /** The time window in days. */
+ window_days: number
+ /**
+ * For regulars: how many times the event must happen in the window.
+ * @nullable
+ */
+ min_count: number | null
+ /** People in the audience with an email address, counted when the suggestion was made. */
+ reachable_count: number
+ /** The audience's cohort filters, in the cohorts endpoint's `filters` format. Saved as a static cohort. */
+ cohort_filters: unknown
+}
+
+export interface AudienceSuggestionsResponseApi {
+ /** ready when suggestions were made (the list can still be empty), generating while a background run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI data processing, unavailable when nothing was made or the run failed.
+ *
+ * * `ready` - Ready
+ * * `generating` - Generating
+ * * `ai_not_approved` - Ai Not Approved
+ * * `unavailable` - Unavailable */
+ status: DataSuggestionsStatusEnumApi
+ /** Up to 3 suggested broadcast audiences. */
+ suggestions: AudienceSuggestionApi[]
+}
+
+export interface DataSuggestionGenerateRequestApi {
+ /** Make new suggestions even when the cached ones are still valid. */
+ refresh?: boolean
+}
+
/**
* * `team` - Only team
* * `organization` - Organization
@@ -2419,22 +2501,6 @@ export interface DataSuggestionBuildResponseApi {
missing_inputs: DataSuggestionMissingInputApi[]
}
-/**
- * * `ready` - Ready
- * * `generating` - Generating
- * * `ai_not_approved` - Ai Not Approved
- * * `unavailable` - Unavailable
- */
-export type DataSuggestionsStatusEnumApi =
- (typeof DataSuggestionsStatusEnumApi)[keyof typeof DataSuggestionsStatusEnumApi]
-
-export const DataSuggestionsStatusEnumApi = {
- Ready: 'ready',
- Generating: 'generating',
- AiNotApproved: 'ai_not_approved',
- Unavailable: 'unavailable',
-} as const
-
/**
* * `signup` - Signup
* * `onboarding` - Onboarding
@@ -2530,11 +2596,6 @@ export interface DataSuggestionsResponseApi {
readonly email_sender_ready: boolean
}
-export interface DataSuggestionGenerateRequestApi {
- /** Make new suggestions even when the cached ones are still valid. */
- refresh?: boolean
-}
-
/**
* * `error_tracking` - Error tracking issue
* * `early_access` - Early access feature
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 09a57a9494c6..09944a1bfb0f 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
AppMetricsTotalsResponseApi,
ApplyUtmDefaultsRequestApi,
ApplyUtmDefaultsResponseApi,
+ AudienceSuggestionsResponseApi,
BlastRadiusApi,
BlastRadiusRequestApi,
BroadcastConversionCandidatesApi,
@@ -122,6 +123,43 @@ export const internalHogFlowsProcessDueSchedulesCreate = async (options?: Reques
})
}
+export const getBroadcastAudienceSuggestionsCurrentUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/broadcast_audience_suggestions/current/`
+}
+
+/**
+ * Broadcast audiences written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const broadcastAudienceSuggestionsCurrent = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<AudienceSuggestionsResponseApi> => {
+ return apiMutator<AudienceSuggestionsResponseApi>(getBroadcastAudienceSuggestionsCurrentUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getBroadcastAudienceSuggestionsGenerateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/broadcast_audience_suggestions/generate/`
+}
+
+/**
+ * Broadcast audiences written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const broadcastAudienceSuggestionsGenerate = async (
+ projectId: string,
+ dataSuggestionGenerateRequestApi?: DataSuggestionGenerateRequestApi,
+ options?: RequestInit
+): Promise<AudienceSuggestionsResponseApi> => {
+ return apiMutator<AudienceSuggestionsResponseApi>(getBroadcastAudienceSuggestionsGenerateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataSuggestionGenerateRequestApi),
+ })
+}
+
export const getHogFlowTemplatesListUrl = (projectId: string, params?: HogFlowTemplatesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 565ec0562f9a..aada0d029824 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -9,6 +9,18 @@
*/
import * as zod from 'zod'
+/**
+ * Broadcast audiences written by AI from the project's own events. Both calls are free for the customer.
+ */
+export const broadcastAudienceSuggestionsGenerateBodyRefreshDefault = false
+
+export const BroadcastAudienceSuggestionsGenerateBody = /* @__PURE__ */ zod.object({
+ refresh: zod
+ .boolean()
+ .default(broadcastAudienceSuggestionsGenerateBodyRefreshDefault)
+ .describe('Make new suggestions even when the cached ones are still valid.'),
+})
+
export const hogFlowTemplatesCreateBodyNameMax = 400
export const hogFlowTemplatesCreateBodyImageUrlMax = 8201
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 35ace8d52cb5..786937887b82 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14311,6 +14311,83 @@ export namespace Schemas {
PositionBased: 'position_based',
} as const;
+ /**
+ * * `not_yet` - Not Yet
+ * * `regulars` - Regulars
+ * * `lapsed` - Lapsed
+ */
+ export type AudienceSuggestionKindEnum = typeof AudienceSuggestionKindEnum[keyof typeof AudienceSuggestionKindEnum];
+
+
+ export const AudienceSuggestionKindEnum = {
+ NotYet: 'not_yet',
+ Regulars: 'regulars',
+ Lapsed: 'lapsed',
+ } as const;
+
+ export interface AudienceSuggestion {
+ /** Opaque id of this suggestion, valid while the suggestions stay cached. */
+ id: string;
+ /** Suggested audience name, written by AI from the project's events. */
+ name: string;
+ /** Who the people are and what to tell them. Used as the cohort description and the email brief. */
+ description: string;
+ /** One sentence on why the audience is worth a broadcast. */
+ reason: string;
+ /** not_yet: did event in the window but not missing_event. regulars: did event at least min_count times in the window. lapsed: did event in the last 90 days but not in the window.
+ *
+ * * `not_yet` - Not Yet
+ * * `regulars` - Regulars
+ * * `lapsed` - Lapsed */
+ kind: AudienceSuggestionKindEnum;
+ /** The project event the audience is built on. */
+ event: string;
+ /**
+ * For not_yet: the event the audience has not done yet. Null otherwise.
+ * @nullable
+ */
+ missing_event: string | null;
+ /** The time window in days. */
+ window_days: number;
+ /**
+ * For regulars: how many times the event must happen in the window.
+ * @nullable
+ */
+ min_count: number | null;
+ /** People in the audience with an email address, counted when the suggestion was made. */
+ reachable_count: number;
+ /** The audience's cohort filters, in the cohorts endpoint's `filters` format. Saved as a static cohort. */
+ cohort_filters: unknown;
+ }
+
+ /**
+ * * `ready` - Ready
+ * * `generating` - Generating
+ * * `ai_not_approved` - Ai Not Approved
+ * * `unavailable` - Unavailable
+ */
+ export type DataSuggestionsStatusEnum = typeof DataSuggestionsStatusEnum[keyof typeof DataSuggestionsStatusEnum];
+
+
+ export const DataSuggestionsStatusEnum = {
+ Ready: 'ready',
+ Generating: 'generating',
+ AiNotApproved: 'ai_not_approved',
+ Unavailable: 'unavailable',
+ } as const;
+
+ export interface AudienceSuggestionsResponse {
+ /** ready when suggestions were made (the list can still be empty), generating while a background run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI data processing, unavailable when nothing was made or the run failed.
+ *
+ * * `ready` - Ready
+ * * `generating` - Generating
+ * * `ai_not_approved` - Ai Not Approved
+ * * `unavailable` - Unavailable */
+ status: DataSuggestionsStatusEnum;
+ /** Up to 3 suggested broadcast audiences. */
+ suggestions: AudienceSuggestion[];
+ }
+
export interface AuditActorServiceAccount {
/** Service account id. */
id: string;
@@ -31548,22 +31625,6 @@ export namespace Schemas {
refresh?: boolean;
}
- /**
- * * `ready` - Ready
- * * `generating` - Generating
- * * `ai_not_approved` - Ai Not Approved
- * * `unavailable` - Unavailable
- */
- export type DataSuggestionsStatusEnum = typeof DataSuggestionsStatusEnum[keyof typeof DataSuggestionsStatusEnum];
-
-
- export const DataSuggestionsStatusEnum = {
- Ready: 'ready',
- Generating: 'generating',
- AiNotApproved: 'ai_not_approved',
- Unavailable: 'unavailable',
- } as const;
-
export interface DataSuggestionsResponse {
/** ready when suggestions were made (the list can still be empty), generating while a background run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI data processing, unavailable when nothing was made or the run failed.
*