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): bill product_analytics and survey AI usage as Max credits (#62631)

Paul D'Ambrab751c06c84bc
diff --git a/posthog/hogql/ai.py b/posthog/hogql/ai.py
index b1a4bf5102da..47f5ccdecbbf 100644
--- a/posthog/hogql/ai.py
+++ b/posthog/hogql/ai.py
@@ -234,7 +234,7 @@ def write_sql_from_prompt(
raise PromptUnclear(error)
-def hit_openai(messages, user, posthog_properties=None) -> tuple[str, int, int]:
+def hit_openai(messages, user, posthog_properties=None, posthog_groups=None) -> tuple[str, int, int]:
if not openai_client:
raise ValueError("OPENAI_API_KEY environment variable not set")
@@ -244,6 +244,7 @@ def hit_openai(messages, user, posthog_properties=None) -> tuple[str, int, int]:
messages=messages,
user=user, # The user ID is for tracking within OpenAI in case of overuse/abuse
posthog_properties=posthog_properties,
+ posthog_groups=posthog_groups,
)
content: str = ""
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 67aa5265f746..2f9e592005fa 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -4304,9 +4304,17 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
# 3.0 USD * 100 * 1.2 = 360
self.assertEqual(result, [(self.org_1_team_1.id, 360)])
+ @parameterized.expand(
+ [
+ ("slack_app",),
+ ("product_analytics",),
+ ("surveys",),
+ ("subscriptions",),
+ ]
+ )
@patch("posthog.tasks.usage_report.get_instance_region")
- def test_ai_credits_counts_traceless_whitelisted_product(self, mock_region: MagicMock) -> None:
- """A traceless whitelisted product (e.g. slack_app) bills via the empty-trace fallback."""
+ def test_traceless_whitelisted_product_bills_as_ai_credits(self, ai_product: str, mock_region: MagicMock) -> None:
+ """A traceless whitelisted product (e.g. slack_app, product_analytics) bills via the empty-trace fallback."""
from posthog.tasks.usage_report import get_teams_with_ai_credits_used_in_period
mock_region.return_value = "US"
@@ -4318,18 +4326,18 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse
period = get_previous_day(at=now() + relativedelta(days=1))
period_start, period_end = period
- # slack_app emits no $ai_trace — billed via the empty-trace fallback, not a paired trace.
+ # These products emit no $ai_trace — billed via the empty-trace fallback, not a paired trace.
_create_event(
event="$ai_generation",
team=analytics_team,
- distinct_id="user_slack",
+ distinct_id=f"user_{ai_product}",
timestamp=period_start + relativedelta(hours=1),
properties={
"team_id": self.org_1_team_1.id,
- "$ai_trace_id": "trace_slack",
+ "$ai_trace_id": f"trace_{ai_product}",
"$ai_total_cost_usd": 1.0,
"$ai_billable": True,
- "ai_product": "slack_app",
+ "ai_product": ai_product,
"$group_1": "https://us.posthog.com",
},
)
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 9860a8d51497..99ef74294068 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -1138,6 +1138,8 @@ POSTHOG_AI_PRODUCTS = [
"slack_app",
"subscriptions",
"alert_investigation_agent",
+ "product_analytics",
+ "surveys",
]
# ai_product values billed as signals credits.
diff --git a/products/exports/backend/temporal/subscriptions/llm_change_summary.py b/products/exports/backend/temporal/subscriptions/llm_change_summary.py
index 8810cbe86bd6..e3a19f34732b 100644
--- a/products/exports/backend/temporal/subscriptions/llm_change_summary.py
+++ b/products/exports/backend/temporal/subscriptions/llm_change_summary.py
@@ -16,6 +16,7 @@ from prometheus_client import Counter
if TYPE_CHECKING:
from posthog.models.team.team import Team
+from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.security.llm_prompt_sanitization import (
INSIGHT_DESCRIPTION_MAX_LEN,
@@ -421,7 +422,7 @@ def generate_change_summary(
if team is not None:
posthog_properties["$ai_billable"] = True
posthog_properties["team_id"] = team.id
- extra_capture_kwargs["posthog_groups"] = {"project": str(team.id)}
+ extra_capture_kwargs["posthog_groups"] = {"project": str(team.id), **groups()}
result = client.chat.completions.create( # type: ignore[call-overload]
model="gpt-4.1-mini",
diff --git a/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py
index 37421ab88c81..649a9adb0464 100644
--- a/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py
+++ b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py
@@ -474,6 +474,28 @@ class TestGenerateChangeSummary:
assert call_kwargs.kwargs["temperature"] == 0.3
assert call_kwargs.kwargs["max_tokens"] == 500
+ @patch("posthog.event_usage.SITE_URL", "https://us.posthog.com")
+ @patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")
+ def test_generation_is_tagged_billable(self, mock_get_client):
+ mock_client = mock_get_client.return_value
+ mock_client.chat.completions.create.return_value = _mock_openai_response("- summary", 10, 5)
+
+ team = MagicMock()
+ team.id = 42
+
+ generate_change_summary(
+ [_make_state(1, "X", "data")],
+ [_make_state(1, "X", "data", timestamp="2025-04-15T10:00:00Z")],
+ team=team,
+ )
+
+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs
+ properties = call_kwargs["posthog_properties"]
+ assert properties["$ai_billable"] is True
+ assert properties["team_id"] == 42
+ assert properties["ai_product"] == "subscriptions"
+ assert call_kwargs["posthog_groups"] == {"project": "42", "instance": "https://us.posthog.com"}
+
@patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_uses_initial_prompt_when_no_previous_states(self, mock_get_client):
mock_client = mock_get_client.return_value
@@ -623,6 +645,7 @@ class TestGenerateChangeSummary:
user_tag = mock_client.chat.completions.create.call_args.kwargs["user"]
assert user_tag.endswith("-delivery-abc-123")
+ @patch("posthog.event_usage.SITE_URL", "https://us.posthog.com")
@patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_marks_generation_billable_to_team_when_team_provided(self, mock_get_client):
mock_client = mock_get_client.return_value
@@ -638,7 +661,7 @@ class TestGenerateChangeSummary:
assert call_kwargs["posthog_properties"]["team_id"] == 42
assert call_kwargs["posthog_properties"]["ai_product"] == "subscriptions"
assert call_kwargs["posthog_properties"]["delivery_id"] == "abc-123"
- assert call_kwargs["posthog_groups"] == {"project": "42"}
+ assert call_kwargs["posthog_groups"] == {"project": "42", "instance": "https://us.posthog.com"}
assert call_kwargs["posthog_distinct_id"] == call_kwargs["user"]
@patch("products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client")
@@ -666,6 +689,7 @@ class TestGenerateChangeSummary:
from unittest.mock import MagicMock
monkeypatch.setenv("OPENAI_API_KEY", "test-fake-key")
+ monkeypatch.setattr("posthog.event_usage.SITE_URL", "https://us.posthog.com")
captured_calls: list[dict] = []
@@ -705,7 +729,7 @@ class TestGenerateChangeSummary:
assert captured["properties"]["$ai_billable"] is True
assert captured["properties"]["team_id"] == 42
assert captured["properties"]["ai_product"] == "subscriptions"
- assert captured["groups"] == {"project": "42"}
+ assert captured["groups"] == {"project": "42", "instance": "https://us.posthog.com"}
class TestAnnotationsSection:
diff --git a/products/product_analytics/backend/api/ai_billing.py b/products/product_analytics/backend/api/ai_billing.py
new file mode 100644
index 000000000000..e49206fb1e3d
--- /dev/null
+++ b/products/product_analytics/backend/api/ai_billing.py
@@ -0,0 +1,7 @@
+def billable_ai_properties(team_id: int, ai_feature: str) -> dict[str, object]:
+ return {
+ "ai_product": "product_analytics",
+ "ai_feature": ai_feature,
+ "$ai_billable": True,
+ "team_id": team_id,
+ }
diff --git a/products/product_analytics/backend/api/insight_metadata.py b/products/product_analytics/backend/api/insight_metadata.py
index 325ca38fee40..e47808ef25cb 100644
--- a/products/product_analytics/backend/api/insight_metadata.py
+++ b/products/product_analytics/backend/api/insight_metadata.py
@@ -16,8 +16,11 @@ from posthog.schema import (
from posthog.hogql.ai import hit_openai
+from posthog.event_usage import groups
from posthog.models import Team
+from products.product_analytics.backend.api.ai_billing import billable_ai_properties
+
class InsightMetadata(BaseModel):
name: str
@@ -495,10 +498,8 @@ def _request_metadata_from_llm(query_summary: str, type_guidance: str, team: Tea
content, _, _ = hit_openai(
messages,
f"team/{team.id}/generate-insight-metadata",
- posthog_properties={
- "ai_product": "product_analytics",
- "ai_feature": "insight-ai-metadata-generation",
- },
+ posthog_properties=billable_ai_properties(team.id, "insight-ai-metadata-generation"),
+ posthog_groups=groups(),
)
parsed = json.loads(content.strip())
diff --git a/products/product_analytics/backend/api/insight_suggestions.py b/products/product_analytics/backend/api/insight_suggestions.py
index 5459695f1400..f3b5e148dbbc 100644
--- a/products/product_analytics/backend/api/insight_suggestions.py
+++ b/products/product_analytics/backend/api/insight_suggestions.py
@@ -18,9 +18,11 @@ from posthog.schema import (
from posthog.hogql.ai import hit_openai
+from posthog.event_usage import groups
from posthog.models import Team
from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_query_date_range
+from products.product_analytics.backend.api.ai_billing import billable_ai_properties
logger = structlog.get_logger(__name__)
@@ -249,7 +251,8 @@ def get_insight_analysis(
content, _, _ = hit_openai(
messages,
f"team/{team.id}/analysis",
- posthog_properties={"ai_product": "product_analytics", "ai_feature": "insight-ai-analysis"},
+ posthog_properties=billable_ai_properties(team.id, "insight-ai-analysis"),
+ posthog_groups=groups(),
)
return content
@@ -298,7 +301,8 @@ def get_ai_suggestions(
content, _, _ = hit_openai(
messages,
f"team/{team.id}/suggestions",
- posthog_properties={"ai_product": "product_analytics", "ai_feature": "insight-ai-suggestions"},
+ posthog_properties=billable_ai_properties(team.id, "insight-ai-suggestions"),
+ posthog_groups=groups(),
)
# Parse JSON from content
diff --git a/products/product_analytics/backend/api/test/test_insight_metadata.py b/products/product_analytics/backend/api/test/test_insight_metadata.py
index 684a734c31a0..3493fad8542f 100644
--- a/products/product_analytics/backend/api/test/test_insight_metadata.py
+++ b/products/product_analytics/backend/api/test/test_insight_metadata.py
@@ -31,6 +31,20 @@ class TestGenerateInsightMetadata(APIBaseTest):
assert response.json()["name"] == "Daily Pageviews"
assert response.json()["description"] == "Tracks daily page views."
+ @patch("posthog.event_usage.SITE_URL", "https://us.posthog.com")
+ @patch(MOCK_PATH)
+ def test_generation_is_tagged_billable(self, mock_openai):
+ mock_openai.return_value = ('{"name": "Daily Pageviews", "description": "Tracks daily page views."}', 10, 20)
+ response = self.client.post(self.url, {"query": _trends_query()}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK
+ properties = mock_openai.call_args.kwargs["posthog_properties"]
+ assert properties["$ai_billable"] is True
+ assert properties["team_id"] == self.team.id
+ assert properties["ai_product"] == "product_analytics"
+ assert properties["ai_feature"] == "insight-ai-metadata-generation"
+ assert mock_openai.call_args.kwargs["posthog_groups"] == {"instance": "https://us.posthog.com"}
+
def test_missing_query_returns_400(self):
response = self.client.post(self.url, {}, format="json")
diff --git a/products/surveys/backend/llm/client.py b/products/surveys/backend/llm/client.py
index 25c31998ad71..82f18935b0b2 100644
--- a/products/surveys/backend/llm/client.py
+++ b/products/surveys/backend/llm/client.py
@@ -12,6 +12,8 @@ from posthoganalytics.ai.gemini import genai
from pydantic import BaseModel
from rest_framework import exceptions
+from posthog.event_usage import groups
+
logger = structlog.get_logger(__name__)
T = TypeVar("T", bound=BaseModel)
@@ -42,6 +44,7 @@ def generate_structured_output(
posthog_properties: dict | None = None,
team_id: int | None = None,
distinct_id: str | None = None,
+ billable: bool = False,
) -> tuple[T, str]:
client = create_gemini_client()
@@ -52,7 +55,12 @@ def generate_structured_output(
)
trace_id = str(uuid.uuid4())
- properties = posthog_properties or {}
+ properties = {**(posthog_properties or {})}
+ posthog_groups = {"project": str(team_id)} if team_id else {}
+ if billable and team_id is not None:
+ properties["team_id"] = team_id
+ properties["$ai_billable"] = True
+ posthog_groups.update(groups())
try:
response = client.models.generate_content(
@@ -62,7 +70,7 @@ def generate_structured_output(
posthog_distinct_id=distinct_id or "",
posthog_trace_id=trace_id,
posthog_properties=properties,
- posthog_groups={"project": str(team_id)} if team_id else {},
+ posthog_groups=posthog_groups,
)
if not response.text:
diff --git a/products/surveys/backend/summarization/llm/gemini.py b/products/surveys/backend/summarization/llm/gemini.py
index 62acc1355c86..6d9c95cdaeb1 100644
--- a/products/surveys/backend/summarization/llm/gemini.py
+++ b/products/surveys/backend/summarization/llm/gemini.py
@@ -84,10 +84,12 @@ def summarize_with_gemini(
"survey_id": survey_id,
"question_id": question_id,
"response_count": len(responses),
- "ai_product": "survey_summary",
+ "ai_product": "surveys",
+ "ai_feature": "survey_summary",
},
team_id=team_id,
distinct_id=distinct_id,
+ billable=True,
)
return SummarizationResult(summary=summary, trace_id=trace_id)
diff --git a/products/surveys/backend/summarization/test_summarization.py b/products/surveys/backend/summarization/test_summarization.py
index 7e4421ff0a16..849fbc01a1fc 100644
--- a/products/surveys/backend/summarization/test_summarization.py
+++ b/products/surveys/backend/summarization/test_summarization.py
@@ -1,5 +1,7 @@
"""Tests for survey summarization module."""
+import json
+
import pytest
from unittest.mock import MagicMock, patch
@@ -122,3 +124,41 @@ class TestSummarizeWithGemini:
assert isinstance(result.summary, SurveySummaryResponse)
assert result.trace_id is not None
assert len(result.trace_id) == 36 # UUID format
+
+ @patch("posthog.event_usage.SITE_URL", "https://us.posthog.com")
+ @patch("products.surveys.backend.llm.client.create_gemini_client")
+ def test_generation_is_tagged_billable(self, mock_create_client):
+ mock_client = MagicMock()
+ mock_create_client.return_value = mock_client
+ valid_response = {
+ "overview": "Users want better performance",
+ "themes": [{"theme": "Speed", "description": "Fast loading times", "frequency": ">50%"}],
+ "key_insight": "Focus on performance",
+ }
+ mock_client.models.generate_content.return_value = MagicMock(text=json.dumps(valid_response))
+
+ summarize_with_gemini("What do you want?", ["Make it faster"], team_id=42)
+
+ call_kwargs = mock_client.models.generate_content.call_args.kwargs
+ properties = call_kwargs["posthog_properties"]
+ assert properties["$ai_billable"] is True
+ assert properties["team_id"] == 42
+ assert properties["ai_product"] == "surveys"
+ assert properties["ai_feature"] == "survey_summary"
+ assert call_kwargs["posthog_groups"] == {"project": "42", "instance": "https://us.posthog.com"}
+
+ @patch("products.surveys.backend.llm.client.create_gemini_client")
+ def test_generation_not_billable_without_team_id(self, mock_create_client):
+ mock_client = MagicMock()
+ mock_create_client.return_value = mock_client
+ valid_response = {
+ "overview": "Users want better performance",
+ "themes": [{"theme": "Speed", "description": "Fast loading times", "frequency": ">50%"}],
+ "key_insight": "Focus on performance",
+ }
+ mock_client.models.generate_content.return_value = MagicMock(text=json.dumps(valid_response))
+
+ summarize_with_gemini("What do you want?", ["Make it faster"])
+
+ properties = mock_client.models.generate_content.call_args.kwargs["posthog_properties"]
+ assert "$ai_billable" not in properties
diff --git a/products/surveys/backend/test_translation.py b/products/surveys/backend/test_translation.py
index 1c9df9ef524f..22ad2ae5c083 100644
--- a/products/surveys/backend/test_translation.py
+++ b/products/surveys/backend/test_translation.py
@@ -72,6 +72,10 @@ def test_generate_survey_translation_preserves_manual_translations(mock_generate
]
assert trace_id == "trace-1"
assert "description_or_goal" in mock_generate_structured_output.call_args.kwargs["user_prompt"]
+ assert mock_generate_structured_output.call_args.kwargs["billable"] is True
+ assert mock_generate_structured_output.call_args.kwargs["team_id"] == 1
+ assert mock_generate_structured_output.call_args.kwargs["posthog_properties"]["ai_product"] == "surveys"
+ assert mock_generate_structured_output.call_args.kwargs["posthog_properties"]["ai_feature"] == "survey_translation"
@patch("products.surveys.backend.translation.generate_structured_output")
diff --git a/products/surveys/backend/translation.py b/products/surveys/backend/translation.py
index ad004873d6e8..7142f72085a8 100644
--- a/products/surveys/backend/translation.py
+++ b/products/surveys/backend/translation.py
@@ -197,9 +197,14 @@ def generate_survey_translation(
f"Questions: {questions}"
),
response_schema=SurveyTranslationResponse,
- posthog_properties={"ai_product": "survey_translation", "target_language": target_language},
+ posthog_properties={
+ "ai_product": "surveys",
+ "ai_feature": "survey_translation",
+ "target_language": target_language,
+ },
team_id=team_id,
distinct_id=distinct_id,
+ billable=True,
)
translations, question_patches, generated_paths = _filter_existing_fields(