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(billing): meter every $ai_* event as an AI event on both surfaces (#103256)

Eli Reismanbea153b63aea
diff --git a/nodejs/src/ingestion/common/ai-event-types.ts b/nodejs/src/ingestion/common/ai-event-types.ts
index a1228c128079..4f63f7170b5a 100644
--- a/nodejs/src/ingestion/common/ai-event-types.ts
+++ b/nodejs/src/ingestion/common/ai-event-types.ts
@@ -7,21 +7,6 @@ export function isAiEventName(event: string): boolean {
return event.startsWith(AI_EVENT_NAME_PREFIX)
}
-// Billing only (billable-events.ts); ingestion uses `isAiEventName`.
-export const AI_EVENT_TYPES = new Set([
- '$ai_generation',
- '$ai_embedding',
- '$ai_evaluation',
- '$ai_span',
- '$ai_trace',
- '$ai_metric',
- '$ai_feedback',
- '$ai_tag',
- '$ai_generation_summary',
- '$ai_trace_summary',
- '$ai_evaluation_report',
-])
-
// Anything that writes a cost onto an event must gate on this set. A cost on any
// other event type is never priced or labeled by processCost, and the AI
// observability usage report sums $ai_total_cost_usd across every AI event type,
diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.test.ts b/nodejs/src/ingestion/common/usage-records/billable-events.test.ts
index 2d3d573e28e5..8461968fa4a5 100644
--- a/nodejs/src/ingestion/common/usage-records/billable-events.test.ts
+++ b/nodejs/src/ingestion/common/usage-records/billable-events.test.ts
@@ -12,9 +12,10 @@ describe('usage key resolvers', () => {
['custom event', EVENTS_USAGE_KEY],
['$ai_generation', AI_EVENTS_USAGE_KEY],
['$ai_trace', AI_EVENTS_USAGE_KEY],
- // Not a known AI event name, so it bills as a standard event — matching the nightly report,
- // which excludes the exact AIEventType values rather than everything prefixed `$ai_`.
- ['$ai_not_a_real_event', EVENTS_USAGE_KEY],
+ // Any `$ai_*` name bills as an AI event, matching the nightly report's prefix split.
+ ['$ai_not_a_real_event', AI_EVENTS_USAGE_KEY],
+ ['ai_generation', EVENTS_USAGE_KEY],
+ ['$AI_generation', EVENTS_USAGE_KEY],
['$feature_flag_called', null],
['$experiment_exposure', null],
['survey sent', SURVEY_RESPONSES_USAGE_KEY],
diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.ts b/nodejs/src/ingestion/common/usage-records/billable-events.ts
index 0423e422161c..2313bdd18f7f 100644
--- a/nodejs/src/ingestion/common/usage-records/billable-events.ts
+++ b/nodejs/src/ingestion/common/usage-records/billable-events.ts
@@ -1,4 +1,4 @@
-import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
+import { isAiEventName } from '~/ingestion/common/ai-event-types'
export const EVENTS_USAGE_KEY = 'events'
export const AI_EVENTS_USAGE_KEY = 'ai_events'
@@ -8,9 +8,8 @@ export const SURVEY_RESPONSES_USAGE_KEY = 'survey_responses'
/** Null means the event is not billed at all. */
export type UsageKeyResolver = (event: string) => string | null
-// Mirrors BILLABLE_EVENT_EXCLUDED_EVENTS in posthog/tasks/usage_report.py, minus the AI events,
-// which are billed under their own key rather than excluded. The two lists have to agree or the
-// usage records and the org usage report bill the same team differently.
+// Mirrors BILLABLE_EVENT_EXCLUDED_EVENTS in posthog/tasks/usage_report.py. The two lists have to
+// agree or the usage records and the org usage report bill the same team differently.
const NON_BILLABLE_EVENTS = new Set([
'$feature_flag_called',
'$experiment_exposure',
@@ -29,11 +28,11 @@ const NON_BILLABLE_EVENTS = new Set([
/**
* Bills each event under the key its own product owns, wherever the event turns up.
- * Matching the exact AI event names rather than the `$ai_` prefix keeps an unknown
- * `$ai_*` event billable as a standard event, which is what the nightly report does.
+ * Every `$ai_*` event bills as an AI event, matching the nightly report's
+ * `startsWith(event, '$ai_')` split between the two meters.
*/
export const resolveAnalyticsUsageKey: UsageKeyResolver = (event) => {
- if (AI_EVENT_TYPES.has(event)) {
+ if (isAiEventName(event)) {
return AI_EVENTS_USAGE_KEY
}
if (event === 'survey sent') {
diff --git a/nodejs/src/ingestion/pipelines/ai/index.ts b/nodejs/src/ingestion/pipelines/ai/index.ts
index 3231b188393d..de873c9f5b65 100644
--- a/nodejs/src/ingestion/pipelines/ai/index.ts
+++ b/nodejs/src/ingestion/pipelines/ai/index.ts
@@ -1,4 +1,3 @@
export { normalizeTraceProperties, processAiEvent, type EventWithProperties } from './process-ai-event'
-export { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'
export { createAiIngestionPipeline, type AiIngestionPipelineConfig } from './pipeline'
export { createAiConsumer, type AiConsumerConfig, type AiSharedScope } from './consumer'
diff --git a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
index 3678bce9f8d4..0b2e017db829 100644
--- a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.test.ts
@@ -10,16 +10,12 @@ jest.mock('~/common/utils/posthog', () => ({
captureException: jest.fn(),
}))
-jest.mock('~/ingestion/pipelines/ai/process-ai-event', () => {
- const actual = jest.requireActual('~/ingestion/pipelines/ai/process-ai-event')
- return {
- AI_EVENT_TYPES: actual.AI_EVENT_TYPES,
- processAiEvent: jest.fn((event: PluginEvent) => ({
- ...event,
- properties: { ...event.properties, $ai_was_processed: true },
- })),
- }
-})
+jest.mock('~/ingestion/pipelines/ai/process-ai-event', () => ({
+ processAiEvent: jest.fn((event: PluginEvent) => ({
+ ...event,
+ properties: { ...event.properties, $ai_was_processed: true },
+ })),
+}))
const mockedProcessAiEvent = processAiEvent as jest.MockedFunction<typeof processAiEvent>
const mockedCaptureException = captureException as jest.MockedFunction<typeof captureException>
diff --git a/posthog/constants.py b/posthog/constants.py
index efabac260dc9..152b873d2e54 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -7,6 +7,10 @@ FROZEN_POSTHOG_VERSION = Version("1.43.0") # Frozen at the last self-hosted ver
INTERNAL_BOT_EMAIL_SUFFIX = "@posthogbot.user"
POSTHOG_INTERNAL_EMAIL_SUFFIX = "@posthog.com"
+# Any `$ai_*` event is an AI event: capture and the AI pipeline route on it, and billing meters
+# it as LLM analytics. nodejs `AI_EVENT_NAME_PREFIX` and Rust `AI_LANE_NAME_PREFIX` pin the same literal.
+AI_EVENT_NAME_PREFIX = "$ai_"
+
# N.B. Keep this in sync with frontend enum (types.ts)
# AND ensure it is added to the Billing Service
diff --git a/posthog/tasks/ai_observability_usage_report.py b/posthog/tasks/ai_observability_usage_report.py
index 5710404df57e..7861243174be 100644
--- a/posthog/tasks/ai_observability_usage_report.py
+++ b/posthog/tasks/ai_observability_usage_report.py
@@ -12,6 +12,7 @@ from retry import retry
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.constants import AI_EVENT_NAME_PREFIX
from posthog.exceptions_capture import capture_exception
from posthog.logging.timing import timed_log
from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
@@ -37,6 +38,8 @@ def get_ph_client() -> PostHogClient:
return PostHogClient(PH_US_API_KEY, sync_mode=True)
+# Only team discovery reads this list: it must pick up customer-emitted core events, never
+# server-side artifacts. Every metric below counts by `AI_EVENT_NAME_PREFIX` instead.
AI_EVENTS = [event.value for event in AIEventType]
LLM_PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"
@@ -262,17 +265,25 @@ def get_teams_with_ai_events(
begin: datetime,
end: datetime,
trigger_events: list[str],
+ event_prefix: str | None = None,
) -> list[int]:
"""
Get all team_ids that have at least one AI observability trigger event in the period.
This is a fast query that returns only distinct team_ids, allowing subsequent
queries to filter by team_id and use the primary key index efficiently.
+
+ `event_prefix` widens the match to every event carrying that prefix, in addition to
+ the exact `trigger_events`. Team discovery passes no prefix on purpose: it must only
+ pick up customer-emitted core events, never server-side artifacts.
"""
+ event_predicate = "event IN %(ai_observability_report_trigger_events)s"
+ if event_prefix is not None:
+ event_predicate = f"({event_predicate} OR startsWith(event, %(event_prefix)s))"
query = f"""
SELECT DISTINCT team_id
FROM {events_read_table(use_new_events_schema(None))}
- WHERE event IN %(ai_observability_report_trigger_events)s
+ WHERE {event_predicate}
AND timestamp >= %(begin)s
AND timestamp < %(end)s
"""
@@ -289,6 +300,7 @@ def get_teams_with_ai_events(
query,
{
"ai_observability_report_trigger_events": trigger_events,
+ "event_prefix": event_prefix,
"begin": begin,
"end": end,
},
@@ -427,7 +439,7 @@ def get_all_ai_metrics(
countIf(event = '$ai_evaluation' AND {prop("$ai_evaluation_runtime")} = 'sentiment') as ai_sentiment_evaluation_count
FROM {events_read_table(use_new)}
WHERE team_id IN %(team_ids)s
- AND event IN %(ai_events)s
+ AND startsWith(event, %(ai_event_prefix)s)
AND timestamp >= %(begin)s
AND timestamp < %(end)s
GROUP BY team_id
@@ -437,7 +449,7 @@ def get_all_ai_metrics(
begin,
end,
query_template,
- {"ai_events": AI_EVENTS},
+ {"ai_event_prefix": AI_EVENT_NAME_PREFIX},
num_splits=3,
combine_results_func=_combine_all_metrics_results,
team_ids=team_ids,
@@ -472,7 +484,7 @@ def get_ai_trace_counts(
uniqIf({trace_id}, {trace_id} != '') as ai_trace_count
FROM {events_read_table(use_new)}
WHERE team_id IN %(team_ids)s
- AND event IN %(ai_events)s
+ AND startsWith(event, %(ai_event_prefix)s)
AND timestamp >= %(begin)s
AND timestamp < %(end)s
GROUP BY team_id
@@ -485,7 +497,7 @@ def get_ai_trace_counts(
begin,
end,
query_template,
- {"ai_events": AI_EVENTS},
+ {"ai_event_prefix": AI_EVENT_NAME_PREFIX},
num_splits=1,
team_ids=team_ids,
query_name="Get AI trace counts",
@@ -637,7 +649,7 @@ def get_all_ai_dimension_breakdowns(
sumMap(map({prop("$ai_cost_model_provider")}, toUInt64(1))) as cost_model_provider_breakdown
FROM {events_read_table(use_new)}
WHERE team_id IN %(team_ids)s
- AND event IN %(ai_events)s
+ AND startsWith(event, %(ai_event_prefix)s)
AND timestamp >= %(begin)s
AND timestamp < %(end)s
GROUP BY team_id
@@ -647,7 +659,7 @@ def get_all_ai_dimension_breakdowns(
begin,
end,
query_template,
- {"ai_events": AI_EVENTS},
+ {"ai_event_prefix": AI_EVENT_NAME_PREFIX},
num_splits=4,
combine_results_func=_combine_dimension_breakdown_results,
team_ids=team_ids,
@@ -908,7 +920,9 @@ def _get_all_ai_observability_reports(
# Phase 1: Get all team_ids with report trigger events (fast query)
try:
- team_ids = get_teams_with_ai_events(period.start, period.end, AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS)
+ team_ids = get_teams_with_ai_events(
+ period.start, period.end, AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS, event_prefix=AI_EVENT_NAME_PREFIX
+ )
except Exception:
logger.warning(
"[AIO Usage Error] teams query failed",
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
index d400484dc3a5..6137f6652ecf 100644
--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr
+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
@@ -658,7 +658,8 @@
FROM events
WHERE timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 02:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -670,7 +671,8 @@
FROM events
WHERE timestamp >= '2022-01-10 02:00:00'
AND timestamp < '2022-01-10 04:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -682,7 +684,8 @@
FROM events
WHERE timestamp >= '2022-01-10 04:00:00'
AND timestamp < '2022-01-10 06:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -694,7 +697,8 @@
FROM events
WHERE timestamp >= '2022-01-10 06:00:00'
AND timestamp < '2022-01-10 08:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -706,7 +710,8 @@
FROM events
WHERE timestamp >= '2022-01-10 08:00:00'
AND timestamp < '2022-01-10 10:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -718,7 +723,8 @@
FROM events
WHERE timestamp >= '2022-01-10 10:00:00'
AND timestamp < '2022-01-10 12:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -730,7 +736,8 @@
FROM events
WHERE timestamp >= '2022-01-10 12:00:00'
AND timestamp < '2022-01-10 14:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -782,7 +789,8 @@
FROM events
WHERE timestamp >= '2022-01-10 14:00:00'
AND timestamp < '2022-01-10 16:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -794,7 +802,8 @@
FROM events
WHERE timestamp >= '2022-01-10 16:00:00'
AND timestamp < '2022-01-10 18:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -806,7 +815,8 @@
FROM events
WHERE timestamp >= '2022-01-10 18:00:00'
AND timestamp < '2022-01-10 20:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -818,7 +828,8 @@
FROM events
WHERE timestamp >= '2022-01-10 20:00:00'
AND timestamp < '2022-01-10 22:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -830,7 +841,8 @@
FROM events
WHERE timestamp >= '2022-01-10 22:00:00'
AND timestamp < '2022-01-10 23:59:59'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
GROUP BY team_id
'''
# ---
@@ -842,7 +854,8 @@
FROM events
WHERE timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 02:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -856,7 +869,8 @@
FROM events
WHERE timestamp >= '2022-01-10 02:00:00'
AND timestamp < '2022-01-10 04:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -870,7 +884,8 @@
FROM events
WHERE timestamp >= '2022-01-10 04:00:00'
AND timestamp < '2022-01-10 06:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -884,7 +899,8 @@
FROM events
WHERE timestamp >= '2022-01-10 06:00:00'
AND timestamp < '2022-01-10 08:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -898,7 +914,8 @@
FROM events
WHERE timestamp >= '2022-01-10 08:00:00'
AND timestamp < '2022-01-10 10:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -952,7 +969,8 @@
FROM events
WHERE timestamp >= '2022-01-10 10:00:00'
AND timestamp < '2022-01-10 12:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -966,7 +984,8 @@
FROM events
WHERE timestamp >= '2022-01-10 12:00:00'
AND timestamp < '2022-01-10 14:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -980,7 +999,8 @@
FROM events
WHERE timestamp >= '2022-01-10 14:00:00'
AND timestamp < '2022-01-10 16:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -994,7 +1014,8 @@
FROM events
WHERE timestamp >= '2022-01-10 16:00:00'
AND timestamp < '2022-01-10 18:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -1008,7 +1029,8 @@
FROM events
WHERE timestamp >= '2022-01-10 18:00:00'
AND timestamp < '2022-01-10 20:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -1022,7 +1044,8 @@
FROM events
WHERE timestamp >= '2022-01-10 20:00:00'
AND timestamp < '2022-01-10 22:00:00'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -1036,7 +1059,8 @@
FROM events
WHERE timestamp >= '2022-01-10 22:00:00'
AND timestamp < '2022-01-10 23:59:59'
- AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND event NOT IN ['$feature_flag_called', '$experiment_exposure', 'survey sent', 'survey shown', 'survey dismissed', '$exception', '$llm_prompt_fetched', '$conversations_loaded', '$conversations_widget_loaded', '$conversations_message_sent', '$conversations_user_identified', '$conversations_restore_link_requested', '$conversations_widget_state_changed', '$conversations_back_to_tickets']
+ AND NOT startsWith(event, '$ai_')
AND person_mode IN ('full',
'force_upgrade')
GROUP BY team_id
@@ -1673,7 +1697,7 @@
if(verified, replaceRegexpAll(JSONExtractRaw(properties, '$ai_gateway_relay'), '^"|"$', ''), '') IN ('true',
'1') AS relay
FROM events
- WHERE event IN ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters']
+ WHERE startsWith(event, '$ai_')
AND timestamp >= '2022-01-10 00:00:00'
AND timestamp < '2022-01-10 23:59:59')
GROUP BY team_id
diff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.py
index 1e6698deb3b1..d8200bd7ca50 100644
--- a/posthog/tasks/test/test_ai_observability_usage_report.py
+++ b/posthog/tasks/test/test_ai_observability_usage_report.py
@@ -21,8 +21,10 @@ from posthog.models import Organization, Team
from posthog.models.event.util import create_event
from posthog.ph_client import PH_US_API_KEY
from posthog.tasks.ai_observability_usage_report import (
+ AI_EVENT_NAME_PREFIX,
AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS,
AI_OBSERVABILITY_USAGE_EVENT,
+ LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS,
_get_all_ai_observability_reports,
capture_ai_observability_report,
get_ai_trace_counts,
@@ -196,6 +198,24 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous
# The root-event count stays available as its own signal, so the two can be compared.
assert get_all_ai_metrics(period.start, period.end, team_ids)[self.team.id].ai_trace_event_count == 1
+ def test_unlisted_ai_prefixed_events_count_for_the_report_but_not_for_discovery(self) -> None:
+ distinct_id = str(uuid4())
+ _create_person(distinct_ids=[distinct_id], team=self.team)
+
+ period = get_previous_day()
+ trace_id = str(uuid4())
+ self._create_ai_events(self.team, distinct_id, "$ai_custom_step", 3, properties={"$ai_trace_id": trace_id})
+
+ assert self.team.id not in get_teams_with_ai_events(
+ period.start, period.end, LLM_ANALYTICS_DISCOVERY_TRIGGER_EVENTS
+ )
+
+ team_ids = get_teams_with_ai_events(
+ period.start, period.end, AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS, event_prefix=AI_EVENT_NAME_PREFIX
+ )
+ assert self.team.id in team_ids
+ assert get_ai_trace_counts(period.start, period.end, team_ids)[self.team.id] == 1
+
def test_get_all_ai_metrics_cost_anomaly_counts(self) -> None:
"""Test that cost anomaly counts (total, negative, zero) are correctly calculated."""
distinct_id = str(uuid4())
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index e45d893d12fc..3f02860f1aa6 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -1729,28 +1729,6 @@ class TestQueryUsageReportSQL:
assert result["mcp_missing_capability_events"] == [(1, 6)]
assert result["mcp_initialize_events"] == [(1, 7)]
- @patch("posthog.tasks.usage_report.events_read_table", return_value="events")
- @patch("posthog.tasks.usage_report.get_property_string_expr", return_value=("property_expr", {}))
- @patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
- @patch("posthog.tasks.usage_report.sync_execute", return_value=[])
- def test_get_teams_with_ai_event_count_excludes_conversations_loaded(
- self,
- mock_sync_execute: MagicMock,
- _mock_use_new_events_schema: MagicMock,
- _mock_get_property_string_expr: MagicMock,
- _mock_events_read_table: MagicMock,
- ) -> None:
- from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
-
- begin = datetime(2026, 6, 15, tzinfo=tzutc())
- end = begin + timedelta(days=1)
-
- get_teams_with_ai_event_count_in_period(begin, end)
-
- params = mock_sync_execute.call_args.args[1]
- assert "$conversations_loaded" not in params["ai_events"]
- assert "$conversations_widget_loaded" not in params["ai_events"]
-
@patch("posthog.tasks.usage_report.events_read_table", return_value="events")
@patch("posthog.tasks.usage_report.get_property_string_expr", return_value=("property_expr", {}))
@patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
@@ -6328,6 +6306,19 @@ class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, Test
# AI count should include original 10 + 5 new = 15
self.assertEqual(ai_result[0][1], 15)
+ # An `$ai_*` name outside the hard-coded enum is still an AI event on both meters.
+ for i in range(2):
+ _create_event(
+ event="$ai_custom_step",
+ team=self.team,
+ distinct_id=f"custom_ai_user_{i}",
+ timestamp=self.begin + relativedelta(hours=i + 10),
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(get_teams_with_billable_event_count_in_period(self.begin, self.end)[0][1], baseline_count)
+ self.assertEqual(get_teams_with_ai_event_count_in_period(self.begin, self.end)[0][1], 17)
+
_create_event(
event="$conversations_loaded",
team=self.team,
@@ -6340,7 +6331,7 @@ class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, Test
ai_result_with_conversations = get_teams_with_ai_event_count_in_period(self.begin, self.end)
self.assertEqual(billable_result_with_conversations[0][1], baseline_count)
- self.assertEqual(ai_result_with_conversations[0][1], 15)
+ self.assertEqual(ai_result_with_conversations[0][1], 17)
# Now add a regular event and verify it DOES increase billable count
_create_event(
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 3c6f66427cfd..a4c1cbbd6316 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -30,7 +30,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.cloud_utils import get_cached_instance_license
-from posthog.constants import FlagRequestType
+from posthog.constants import AI_EVENT_NAME_PREFIX, FlagRequestType
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.llm.billing import AI_COST_MARKUP_PERCENT
@@ -43,7 +43,6 @@ from posthog.models.organization import Organization
from posthog.models.property.util import get_property_string_expr
from posthog.models.team.team import Team
from posthog.models.utils import namedtuplefetchall
-from posthog.schema_enums import AIEventType
from posthog.scoping_audit import skip_team_scope_audit
from posthog.settings import CLICKHOUSE_CLUSTER, INSTANCE_TAG
from posthog.tasks.ai_observability_usage_report import LLM_PROMPT_FETCHED_EVENT
@@ -88,9 +87,6 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSchemaSt
logger = structlog.get_logger(__name__)
logging.getLogger(__name__).setLevel(logging.INFO)
-# AI events dynamically generated from AIEventType TS enum
-# Changes to the AIEventType enum will impact usage reporting
-AI_EVENTS = [event.value for event in AIEventType]
GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE = 20
GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE = 20
# Gateway generations are emitted after provider completion. The default gateway
@@ -121,7 +117,6 @@ BILLABLE_EVENT_EXCLUDED_EVENTS = [
# Emitted server-side on each prompt fetch. Prompt management is free, so the event is an
# artifact of using the product rather than customer instrumentation.
LLM_PROMPT_FETCHED_EVENT,
- *AI_EVENTS,
*CONVERSATIONS_EVENTS,
]
@@ -746,12 +741,17 @@ def get_teams_with_billable_event_count_in_period(
FROM {events_read_table(use_new_events_schema(None))}
WHERE timestamp >= %(begin)s AND timestamp < %(end)s
AND event NOT IN %(excluded_events)s
+ AND NOT startsWith(event, %(ai_event_prefix)s)
GROUP BY team_id
"""
with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.USAGE_REPORT):
return _execute_split_query(
- begin, end, query_template, {"excluded_events": BILLABLE_EVENT_EXCLUDED_EVENTS}, num_splits=12
+ begin,
+ end,
+ query_template,
+ {"excluded_events": BILLABLE_EVENT_EXCLUDED_EVENTS, "ai_event_prefix": AI_EVENT_NAME_PREFIX},
+ num_splits=12,
)
@@ -777,13 +777,18 @@ def get_teams_with_billable_enhanced_persons_event_count_in_period(
FROM {events_read_table(use_new_events_schema(None))}
WHERE timestamp >= %(begin)s AND timestamp < %(end)s
AND event NOT IN %(excluded_events)s
+ AND NOT startsWith(event, %(ai_event_prefix)s)
AND person_mode IN ('full', 'force_upgrade')
GROUP BY team_id
"""
with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.USAGE_REPORT):
return _execute_split_query(
- begin, end, query_template, {"excluded_events": BILLABLE_EVENT_EXCLUDED_EVENTS}, num_splits=12
+ begin,
+ end,
+ query_template,
+ {"excluded_events": BILLABLE_EVENT_EXCLUDED_EVENTS, "ai_event_prefix": AI_EVENT_NAME_PREFIX},
+ num_splits=12,
)
@@ -1588,11 +1593,11 @@ def get_teams_with_ai_event_count_in_period(
if(verified, {request_id_expr}, '') AS request_id,
if(verified, {relay_expr}, '') IN ('true', '1') AS relay
FROM {events_read_table(use_new)}
- WHERE event IN %(ai_events)s AND timestamp >= %(begin)s AND timestamp < %(end)s
+ WHERE startsWith(event, %(ai_event_prefix)s) AND timestamp >= %(begin)s AND timestamp < %(end)s
)
GROUP BY team_id
""",
- {"begin": begin, "end": end, "ai_events": AI_EVENTS},
+ {"begin": begin, "end": end, "ai_event_prefix": AI_EVENT_NAME_PREFIX},
workload=Workload.OFFLINE,
settings=CH_BILLING_SETTINGS,
ch_user=ClickHouseUser.BILLING,
@@ -1696,7 +1701,7 @@ def get_teams_with_ai_event_count_in_period(
if(verified AND relay, {span_id_expr}, '') AS span_id
FROM {events_read_table(use_new)}
WHERE team_id IN %(relayed_team_ids)s
- AND event IN %(ai_events)s
+ AND startsWith(event, %(ai_event_prefix)s)
AND timestamp >= %(relay_begin)s AND timestamp < %(sponsor_end)s
AND {verified_expr} IN ('true', '1')
AND {relay_expr} IN ('true', '1')
@@ -1713,7 +1718,7 @@ def get_teams_with_ai_event_count_in_period(
"evaluation_allowance": GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE,
"backdate_seconds": int(GATEWAY_SPONSORSHIP_BACKDATE.total_seconds()),
"relayed_team_ids": relayed_team_ids,
- "ai_events": AI_EVENTS,
+ "ai_event_prefix": AI_EVENT_NAME_PREFIX,
"begin": begin,
"end": end,
"sponsor_begin": begin - GATEWAY_SPONSORSHIP_LOOKAROUND,
diff --git a/products/billing/skills/test_understanding_billing_usage_skill.py b/products/billing/skills/test_understanding_billing_usage_skill.py
index af0e75279796..d1691dc87efc 100644
--- a/products/billing/skills/test_understanding_billing_usage_skill.py
+++ b/products/billing/skills/test_understanding_billing_usage_skill.py
@@ -1,5 +1,6 @@
from pathlib import Path
+from posthog.constants import AI_EVENT_NAME_PREFIX
from posthog.tasks.usage_report import BILLABLE_EVENT_EXCLUDED_EVENTS
SKILL_PATH = Path(__file__).parent / "understanding-billing-usage" / "SKILL.md"
@@ -11,6 +12,7 @@ def test_event_drilldown_excludes_non_billable_events() -> None:
missing_events = [event for event in BILLABLE_EVENT_EXCLUDED_EVENTS if event not in skill_content]
assert missing_events == []
+ assert f"NOT startsWith(event, '{AI_EVENT_NAME_PREFIX}')" in skill_content
def test_product_drilldown_treats_product_data_as_untrusted() -> None:
diff --git a/products/billing/skills/understanding-billing-usage/SKILL.md b/products/billing/skills/understanding-billing-usage/SKILL.md
index 7ebcdf030023..9786813bb191 100644
--- a/products/billing/skills/understanding-billing-usage/SKILL.md
+++ b/products/billing/skills/understanding-billing-usage/SKILL.md
@@ -202,15 +202,12 @@ WHERE timestamp >= {window_start}
'$feature_flag_called', '$experiment_exposure', '$exception',
'survey sent', 'survey shown', 'survey dismissed',
'$llm_prompt_fetched',
- '$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric',
- '$ai_feedback', '$ai_evaluation', '$ai_tag',
- '$ai_trace_summary', '$ai_generation_summary',
- '$ai_trace_clusters', '$ai_generation_clusters',
'$conversations_loaded', '$conversations_widget_loaded',
'$conversations_message_sent', '$conversations_user_identified',
'$conversations_restore_link_requested',
'$conversations_widget_state_changed', '$conversations_back_to_tickets'
)
+ AND NOT startsWith(event, '$ai_')
GROUP BY event
ORDER BY c DESC
LIMIT 20