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(subscriptions): bill AI summaries to customer and double active caps (#57511)

Paul D'Ambra9d77614b5c85
diff --git a/posthog/resource_limits/registry.py b/posthog/resource_limits/registry.py
index 059afb1bd703..06cd729d563c 100644
--- a/posthog/resource_limits/registry.py
+++ b/posthog/resource_limits/registry.py
@@ -70,8 +70,8 @@ REGISTRY: dict[str, LimitDefinition] = {
LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG: LimitDefinition(
key=LimitKey.MAX_ACTIVE_AI_SUMMARIES_PER_ORG,
description="Subscriptions with summary_enabled=True per organization",
- default=10,
- by_plan_tier={"free": 10, "paid": 20, "enterprise": 100},
+ default=20,
+ by_plan_tier={"free": 20, "paid": 40, "enterprise": 200},
),
}
diff --git a/posthog/resource_limits/test/test_evaluator.py b/posthog/resource_limits/test/test_evaluator.py
index b00b03ab4b28..5434ba61780a 100644
--- a/posthog/resource_limits/test/test_evaluator.py
+++ b/posthog/resource_limits/test/test_evaluator.py
@@ -65,9 +65,9 @@ class TestCheckCountLimit(BaseTest):
class TestGetOrganizationLimit(BaseTest):
@parameterized.expand(
[
- ("free_no_features", [], 10),
- ("paid_with_subscriptions", [{"key": AvailableFeature.SUBSCRIPTIONS}], 20),
- ("enterprise_with_saml", [{"key": AvailableFeature.SAML}], 100),
+ ("free_no_features", [], 20),
+ ("paid_with_subscriptions", [{"key": AvailableFeature.SUBSCRIPTIONS}], 40),
+ ("enterprise_with_saml", [{"key": AvailableFeature.SAML}], 200),
]
)
def test_resolves_tiered_limit(
diff --git a/posthog/temporal/subscriptions/llm_change_summary.py b/posthog/temporal/subscriptions/llm_change_summary.py
index 3251aaa9c2ef..a7b227e5cafe 100644
--- a/posthog/temporal/subscriptions/llm_change_summary.py
+++ b/posthog/temporal/subscriptions/llm_change_summary.py
@@ -1,11 +1,16 @@
from __future__ import annotations
+import os
import re
import base64
from dataclasses import dataclass
from typing import TYPE_CHECKING
+from django.conf import settings
+
import structlog
+import posthoganalytics
+from posthoganalytics.ai.openai import OpenAI
from prometheus_client import Counter
if TYPE_CHECKING:
@@ -13,7 +18,6 @@ if TYPE_CHECKING:
from posthog.api.insight_suggestions import get_query_specific_instructions
from posthog.exceptions_capture import capture_exception
-from posthog.llm.gateway_client import get_llm_client
from posthog.models.llm_prompt import normalize_prompt_to_string
from posthog.utils import get_instance_region
@@ -314,6 +318,12 @@ def _attach_images_to_user_message(
return AttachedImageSummary(len(ordered_ids), bytes_total, len(user_text))
+def _get_openai_client() -> OpenAI:
+ if not os.environ.get("OPENAI_API_KEY"):
+ raise ValueError("OPENAI_API_KEY environment variable not set")
+ return OpenAI(posthog_client=posthoganalytics, base_url=settings.OPENAI_BASE_URL, max_retries=3) # type: ignore[arg-type]
+
+
def generate_change_summary(
previous_states: list[dict] | None,
current_states: list[dict],
@@ -343,19 +353,33 @@ def generate_change_summary(
user_message_length=attached.user_text_length,
)
- client = get_llm_client(product="subscriptions")
+ client = _get_openai_client()
instance_region = get_instance_region() or "HOBBY"
user_tag = f"{instance_region}/subscription-summary-team-{team_id}"
if delivery_id:
user_tag = f"{user_tag}-delivery-{delivery_id}"
- result = client.chat.completions.create(
+
+ posthog_properties: dict[str, object] = {"ai_product": "subscriptions"}
+ if delivery_id:
+ posthog_properties["delivery_id"] = delivery_id
+
+ extra_capture_kwargs: dict[str, object] = {}
+ 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)}
+
+ result = client.chat.completions.create( # type: ignore[call-overload]
model="gpt-4.1-mini",
temperature=0.3,
max_tokens=500,
timeout=60,
- messages=messages, # type: ignore[arg-type]
+ messages=messages,
user=user_tag,
+ posthog_distinct_id=user_tag,
+ posthog_properties=posthog_properties,
+ **extra_capture_kwargs,
)
content: str = ""
diff --git a/posthog/temporal/subscriptions/test_llm_change_summary.py b/posthog/temporal/subscriptions/test_llm_change_summary.py
index ccb320469c09..d40080426abb 100644
--- a/posthog/temporal/subscriptions/test_llm_change_summary.py
+++ b/posthog/temporal/subscriptions/test_llm_change_summary.py
@@ -1,3 +1,5 @@
+from types import SimpleNamespace
+
import pytest
from unittest.mock import patch
@@ -273,7 +275,7 @@ def _mock_openai_response(content: str = "", prompt_tokens: int = 0, completion_
class TestGenerateChangeSummary:
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_returns_content_with_correct_params(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response(
@@ -291,7 +293,7 @@ class TestGenerateChangeSummary:
assert call_kwargs.kwargs["temperature"] == 0.3
assert call_kwargs.kwargs["max_tokens"] == 500
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.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
mock_client.chat.completions.create.return_value = _mock_openai_response(
@@ -308,7 +310,7 @@ class TestGenerateChangeSummary:
system_content = messages[0]["content"]
assert "current state" in system_content
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_handles_empty_content(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("", 0, 0)
@@ -320,7 +322,7 @@ class TestGenerateChangeSummary:
assert result == ""
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_attaches_insight_images_as_multimodal_parts(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("- Data shown")
@@ -342,7 +344,7 @@ class TestGenerateChangeSummary:
assert image_parts[0]["image_url"]["url"].startswith("data:image/png;base64,")
assert image_parts[0]["image_url"]["detail"] == "auto"
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_prepends_label_text_part_before_each_image(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
@@ -361,7 +363,7 @@ class TestGenerateChangeSummary:
assert "Chart for: Pageviews" in label_texts
assert "Chart for: Signups" in label_texts
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_preserves_state_order_when_attaching_images(self, mock_get_client):
import base64
@@ -383,7 +385,7 @@ class TestGenerateChangeSummary:
expected_first = f"data:image/png;base64,{base64.b64encode(b'su').decode()}"
assert image_parts[0]["image_url"]["url"] == expected_first
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_leaves_user_message_as_string_when_no_images(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
@@ -395,7 +397,7 @@ class TestGenerateChangeSummary:
messages = mock_client.chat.completions.create.call_args.kwargs["messages"]
assert isinstance(messages[-1]["content"], str)
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_skips_images_for_insights_not_in_current_states(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
@@ -409,7 +411,7 @@ class TestGenerateChangeSummary:
image_parts = [p for p in messages[-1]["content"] if p.get("type") == "image_url"]
assert len(image_parts) == 1
- @patch("posthog.temporal.subscriptions.llm_change_summary.get_llm_client")
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
def test_user_tag_includes_delivery_id_when_provided(self, mock_get_client):
mock_client = mock_get_client.return_value
mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
@@ -420,3 +422,87 @@ class TestGenerateChangeSummary:
user_tag = mock_client.chat.completions.create.call_args.kwargs["user"]
assert user_tag.endswith("-delivery-abc-123")
+
+ @patch("posthog.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
+ mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
+
+ team = SimpleNamespace(id=42)
+ current = [_make_state(1, "Pageviews", "...", timestamp="2025-04-15T10:00:00Z")]
+
+ generate_change_summary(None, current, team=team, delivery_id="abc-123") # type: ignore[arg-type]
+
+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs
+ assert call_kwargs["posthog_properties"]["$ai_billable"] is True
+ 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_distinct_id"] == call_kwargs["user"]
+
+ @patch("posthog.temporal.subscriptions.llm_change_summary._get_openai_client")
+ def test_does_not_mark_billable_when_team_missing(self, mock_get_client):
+ mock_client = mock_get_client.return_value
+ mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")
+
+ current = [_make_state(1, "Pageviews", "...", timestamp="2025-04-15T10:00:00Z")]
+
+ generate_change_summary(None, current, team=None)
+
+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs
+ assert "$ai_billable" not in call_kwargs["posthog_properties"]
+ assert "team_id" not in call_kwargs["posthog_properties"]
+ assert "posthog_groups" not in call_kwargs
+
+ def test_get_openai_client_raises_when_api_key_missing(self, monkeypatch):
+ from posthog.temporal.subscriptions.llm_change_summary import _get_openai_client
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ with pytest.raises(ValueError, match="OPENAI_API_KEY"):
+ _get_openai_client()
+
+ def test_emits_ai_generation_event_with_billing_properties(self, monkeypatch):
+ from unittest.mock import MagicMock
+
+ monkeypatch.setenv("OPENAI_API_KEY", "test-fake-key")
+
+ captured_calls: list[dict] = []
+
+ def fake_capture(*args, **kwargs):
+ captured_calls.append(kwargs)
+
+ monkeypatch.setattr("posthoganalytics.capture", fake_capture)
+
+ usage_details = MagicMock()
+ usage_details.cached_tokens = 0
+ usage_details.reasoning_tokens = 0
+ usage = MagicMock()
+ usage.prompt_tokens = 10
+ usage.completion_tokens = 5
+ usage.prompt_tokens_details = usage_details
+ usage.completion_tokens_details = usage_details
+ choice = MagicMock()
+ choice.message.content = "- ok"
+ choice.message.tool_calls = None
+ choice.finish_reason = "stop"
+ fake_response = MagicMock()
+ fake_response.choices = [choice]
+ fake_response.usage = usage
+ fake_response.model = "gpt-4.1-mini"
+
+ team = SimpleNamespace(id=42)
+ current = [_make_state(1, "Pageviews", "...", timestamp="2025-04-15T10:00:00Z")]
+
+ with patch("openai.resources.chat.completions.Completions.create", return_value=fake_response):
+ generate_change_summary(None, current, team=team, delivery_id="abc-123") # type: ignore[arg-type]
+
+ ai_generation_calls = [c for c in captured_calls if c.get("event") == "$ai_generation"]
+ assert len(ai_generation_calls) == 1, (
+ f"expected exactly one $ai_generation capture, got events: {[c.get('event') for c in captured_calls]}"
+ )
+ captured = ai_generation_calls[0]
+ assert captured["properties"]["$ai_billable"] is True
+ assert captured["properties"]["team_id"] == 42
+ assert captured["properties"]["ai_product"] == "subscriptions"
+ assert captured["groups"] == {"project": "42"}