: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): bill vision action summaries through posthog ai (#69074)
Kim Svatos Dugan07069088736f
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex 6ed1d020b5ec..1d1d90af0b43 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -4385,6 +4385,7 @@ class TestAIEventsUsageReport(ClickhouseDestroyTablesMixin, TestCase, Clickhouse("product_analytics",),("surveys",),("subscriptions",),+ ("replay_vision",),])@patch("posthog.tasks.usage_report.get_instance_region")diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex b1d691f50a0f..d2b717b63629 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -1287,6 +1287,7 @@ POSTHOG_AI_PRODUCTS = ["alert_investigation_agent","product_analytics","surveys",+ "replay_vision",]# ai_product values billed as PostHog Code credits.diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex 5e33bd90f42c..0782939f5130 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -11,23 +11,25 @@ from datetime import UTC, datetime, timedelta, tzinfofrom typing import TYPE_CHECKING, Any, NamedTuplefrom zoneinfo import ZoneInfo+from django.conf import settings+import structlog-from google.genai import types-from posthoganalytics.ai.gemini import genai+import posthoganalytics+from posthoganalytics.ai.openai import OpenAIfrom temporalio import activity+from posthog.event_usage import groupsfrom posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.models.team import Teamfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.sync import database_sync_to_asyncfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel+from products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatusfrom products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, describe_outputfrom products.replay_vision.backend.temporal.constants import replay_vision_distinct_idfrom products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.gemini import gemini_api_keyfrom products.replay_vision.backend.temporal.vision_actions.types import (SynthesisStatus,SynthesizeGroupSummaryInputs,@@ -42,10 +44,10 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-# Track the scanners' default Gemini model so synthesis and scanning move together. Runs through the-# PostHog-instrumented client so the generation lands in LLM analytics attributed to Replay Vision+# Matches how insight AI summaries synthesize: PostHog AI through the LLM gateway+# (settings.OPENAI_BASE_URL), billed to the team's AI credits via the $ai_billable generation event# (see `_run_synthesis`).-SYNTHESIS_MODEL = ScannerModel.GEMINI_3_FLASH.value+SYNTHESIS_MODEL = "gpt-4.1-mini"# Cap how many observations feed one group summary — bounds context size and cost.MAX_OBSERVATIONS = 100# Upper bound on how many ids the sampling path pulls into memory. A very busy window (the case the@@ -336,19 +338,33 @@ def _run_synthesis(team: Team, action: VisionAction, lines: list[str]) -> str:# thing the model reads — nothing instruction-shaped trails it for injected text to blend into.human = prompt_guide + as_untrusted_data("observations", lines)- # Same PostHog-instrumented Gemini client + Replay Vision tagging the scanners use, so the- # generation is captured in LLM analytics attributed to Replay Vision. The enclosing activity's- # start-to-close timeout bounds the call.- client = genai.Client(api_key=gemini_api_key())- response = client.models.generate_content(- model=f"models/{SYNTHESIS_MODEL}",- contents=human,- config=types.GenerateContentConfig(system_instruction=_SYSTEM_PROMPT),- posthog_distinct_id=replay_vision_distinct_id(team.id),- posthog_groups={"project": str(team.id)},- posthog_properties={"ai_product": "replay_vision", "feature": "vision_action_group_summary"},+ # PostHog AI, matching insight AI summaries: the PostHog-instrumented OpenAI client pointed at+ # the LLM gateway (settings.OPENAI_BASE_URL), so the generation lands in LLM analytics tagged to+ # Replay Vision AND bills the team's AI credits ($ai_billable) — the same budget+ # is_team_over_ai_credit_budget gates on above.+ client = OpenAI(posthog_client=posthoganalytics, base_url=settings.OPENAI_BASE_URL, max_retries=3) # type: ignore[arg-type]+ distinct_id = replay_vision_distinct_id(team.id)+ response = client.chat.completions.create( # type: ignore[call-overload]+ model=SYNTHESIS_MODEL,+ temperature=0.3,+ timeout=120,+ messages=[+ {"role": "system", "content": _SYSTEM_PROMPT},+ {"role": "user", "content": human},+ ],+ user=distinct_id,+ posthog_distinct_id=distinct_id,+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "vision_action_group_summary",+ "$ai_billable": True,+ "team_id": team.id,+ },+ posthog_groups={**groups(team=team), "project": str(team.id)},)- return (response.text or "").strip()+ if not response.choices:+ return ""+ return (response.choices[0].message.content or "").strip()def _markdown_to_slack(markdown: str) -> str:diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.pyindex ee00db1dce85..e915a9d60f54 100644--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py@@ -19,24 +19,25 @@ from products.replay_vision.backend.tests.helpers import snapshot_for_SYNTH_PATH = "products.replay_vision.backend.temporal.vision_actions.synthesis"-def _mock_genai(content: str, captured: list[str] | None = None):- # genai.Client(...).models.generate_content(...) → object with .text- def _generate(**kwargs) -> SimpleNamespace:+def _user_message(kwargs: dict) -> str:+ return next((m["content"] for m in kwargs.get("messages", []) if m["role"] == "user"), "")+++def _mock_openai(content: str, captured: list[str] | None = None):+ # OpenAI(...).chat.completions.create(...) → object with .choices[0].message.content+ def _create(**kwargs) -> SimpleNamespace:if captured is not None:- captured.append(kwargs.get("contents", ""))- return SimpleNamespace(text=content)+ captured.append(_user_message(kwargs))+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))])- client = SimpleNamespace(models=SimpleNamespace(generate_content=_generate))- return SimpleNamespace(Client=lambda **_kwargs: client)+ client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=_create)))+ return lambda **_kwargs: clientdef _no_llm_client(**_kwargs):raise AssertionError("LLM should not be called")-_NO_LLM = SimpleNamespace(Client=_no_llm_client)--class TestVisionActionSynthesis(BaseTest):def setUp(self) -> None:super().setUp()@@ -92,7 +93,7 @@ class TestVisionActionSynthesis(BaseTest):):with (patch(f"{_SYNTH_PATH}.is_team_over_ai_credit_budget", return_value=False),- patch(f"{_SYNTH_PATH}.genai", _mock_genai(llm_content, captured_prompts)),+ patch(f"{_SYNTH_PATH}.OpenAI", _mock_openai(llm_content, captured_prompts)),):return _synthesize(SynthesizeGroupSummaryInputs(run_id=run.id, team_id=self.team.id))@@ -249,10 +250,10 @@ class TestVisionActionSynthesis(BaseTest):run.observation_count = 5run.save()- # If the LLM were called, this would raise (genai client patched to blow up).+ # If the LLM were called, this would raise (OpenAI client patched to blow up).with (patch(f"{_SYNTH_PATH}.is_team_over_ai_credit_budget", return_value=False),- patch(f"{_SYNTH_PATH}.genai", _NO_LLM),+ patch(f"{_SYNTH_PATH}.OpenAI", _no_llm_client),):result = _synthesize(SynthesizeGroupSummaryInputs(run_id=run.id, team_id=self.team.id))@@ -286,7 +287,7 @@ class TestVisionActionSynthesis(BaseTest):with (patch(f"{_SYNTH_PATH}.is_team_over_ai_credit_budget", return_value=(gate == "over_budget")),- patch(f"{_SYNTH_PATH}.genai", _NO_LLM),+ patch(f"{_SYNTH_PATH}.OpenAI", _no_llm_client),):result = _synthesize(SynthesizeGroupSummaryInputs(run_id=run.id, team_id=self.team.id))@@ -461,15 +462,15 @@ class TestVisionActionSynthesis(BaseTest):captured: dict = {}def _capturing_client(**_kwargs):- def generate_content(**kwargs):- captured["human"] = kwargs["contents"]- return SimpleNamespace(text="ok")+ def create(**kwargs):+ captured["human"] = _user_message(kwargs)+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))])- return SimpleNamespace(models=SimpleNamespace(generate_content=generate_content))+ return SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create)))with (patch(f"{_SYNTH_PATH}.is_team_over_ai_credit_budget", return_value=False),- patch(f"{_SYNTH_PATH}.genai", SimpleNamespace(Client=_capturing_client)),+ patch(f"{_SYNTH_PATH}.OpenAI", _capturing_client),):_synthesize(SynthesizeGroupSummaryInputs(run_id=run.id, team_id=self.team.id))