: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(aio): attribute internal AI spend to projects (#85516)
Ben Whitef017c5393d44
diff --git a/ee/support_sidebar_max/views.py b/ee/support_sidebar_max/views.pyindex 05addb27f2d7..1424edb0dadc 100644--- a/ee/support_sidebar_max/views.py+++ b/ee/support_sidebar_max/views.py@@ -7,12 +7,14 @@ import loggingimport builtinsfrom collections.abc import MutableMappingfrom datetime import UTC, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom django.conf import settingsimport anthropic+import posthoganalyticsfrom asgiref.sync import sync_to_async+from posthoganalytics.ai.anthropic import Anthropicfrom rest_framework import status, viewsetsfrom rest_framework.authentication import SessionAuthenticationfrom rest_framework.decorators import action@@ -20,6 +22,8 @@ from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.models import User+from ee.support_sidebar_max.prompt import get_system_promptfrom .max_search_tool import max_search_tool@@ -65,12 +69,14 @@ class MaxChatViewSet(viewsets.ViewSet):"""Retrieve endpoint - not used but required by DRF"""return Response({"detail": "Retrieve operation not supported"}, status=status.HTTP_405_METHOD_NOT_ALLOWED)- async def async_send_message(self, client: anthropic.Anthropic, tools, system_prompt, messages):+ async def async_send_message(+ self, client: Anthropic, tools, system_prompt, messages, distinct_id: str, team_id: int | None+ ):"""Async wrapper for send_message"""@sync_to_async(thread_sensitive=False)def _send_message():- return self.send_message(client, tools, system_prompt, messages)+ return self.send_message(client, tools, system_prompt, messages, distinct_id, team_id)return await _send_message()@@ -83,7 +89,14 @@ class MaxChatViewSet(viewsets.ViewSet):return self._handle_rate_limit(retry_after, limit_type)# Initialize Anthropic client (non-blocking)- client = anthropic.Anthropic(api_key=settings.ANTHROPIC_API_KEY, timeout=self.ANTHROPIC_TIMEOUT_SECONDS)+ client = Anthropic(+ api_key=settings.ANTHROPIC_API_KEY,+ posthog_client=posthoganalytics.default_client,+ timeout=self.ANTHROPIC_TIMEOUT_SECONDS,+ )+ user = cast(User, request.user)+ distinct_id = user.distinct_id or str(user.id)+ team_id = user.current_team_iddata = request.dataif not data or "message" not in data:@@ -102,7 +115,7 @@ class MaxChatViewSet(viewsets.ViewSet):if not user_input.strip():history.add_turn_user("Hello!")result = await self.async_send_message(- client, [max_search_tool_tool], system_prompt, history.get_turns()+ client, [max_search_tool_tool], system_prompt, history.get_turns(), distinct_id, team_id)if isinstance(result, Response): # Error responsereturn result@@ -115,7 +128,9 @@ class MaxChatViewSet(viewsets.ViewSet):messages = history.get_turns()full_response = ""- result = await self.async_send_message(client, [max_search_tool_tool], system_prompt, messages)+ result = await self.async_send_message(+ client, [max_search_tool_tool], system_prompt, messages, distinct_id, team_id+ )if isinstance(result, Response): # Error responsereturn result@@ -126,7 +141,7 @@ class MaxChatViewSet(viewsets.ViewSet):messages.append(tool_result)result = await self.async_send_message(- client, [max_search_tool_tool], system_prompt, history.get_turns()+ client, [max_search_tool_tool], system_prompt, history.get_turns(), distinct_id, team_id)if isinstance(result, Response): # Error responsereturn result@@ -231,7 +246,7 @@ class MaxChatViewSet(viewsets.ViewSet):# Return the formatted results and current responsereturn full_response, self._format_tool_result(tool_use_block["id"], formatted_results)- def send_message(self, client: anthropic.Anthropic, tools, system_prompt, messages):+ def send_message(self, client: Anthropic, tools, system_prompt, messages, distinct_id: str, team_id: int | None):"""Send message to Anthropic API with proper error handling"""try:django_logger.info("✨🦔 Preparing to send message to Anthropic API")@@ -258,13 +273,20 @@ class MaxChatViewSet(viewsets.ViewSet):messages = [messages[0], messages[-1]] # Keep first and last messages# Use with_raw_response to get access to headers- raw_response = client.messages.with_raw_response.create(+ raw_response = client.messages.with_raw_response.create( # type: ignore[call-overload]model="claude-3-5-sonnet-20241022",max_tokens=1024,tools=tools,system=system_prompt,messages=messages,extra_headers=headers,+ posthog_privacy_mode=True,+ posthog_distinct_id=distinct_id,+ posthog_properties={+ "ai_product": "support_sidebar_max",+ "ai_feature": "chat",+ "team_id": team_id,+ },)# Get the actual message responsediff --git a/ee/surveys/summaries/summarize_surveys.py b/ee/surveys/summaries/summarize_surveys.pyindex 435f5f3a6980..bc1c1893d033 100644--- a/ee/surveys/summaries/summarize_surveys.py+++ b/ee/surveys/summaries/summarize_surveys.py@@ -1,8 +1,9 @@from datetime import datetimefrom typing import Optional, cast-import openaiimport structlog+import posthoganalytics+from posthoganalytics.ai.openai import OpenAIfrom prometheus_client import Histogramfrom posthog.hogql import ast@@ -92,7 +93,7 @@ def summarize_survey_responses(prepared_data = [x[0] for x in query_response.results if x[0]]with timer("openai_completion"):- result = openai.chat.completions.create(+ result = OpenAI(posthog_client=posthoganalytics.default_client).chat.completions.create( # type: ignore[call-overload]model="gpt-4.1-mini", # allows 128k tokenstemperature=0.7,messages=[@@ -126,6 +127,13 @@ taking into consideration the survey question being asked.},],user=f"{instance_region}/{user.pk}",+ posthog_privacy_mode=True,+ posthog_distinct_id=user.distinct_id,+ posthog_properties={+ "ai_product": "surveys",+ "ai_feature": "response-summary",+ "team_id": team.id,+ },)usage = result.usage.prompt_tokens if result.usage else Nonediff --git a/posthog/api/csp_reporting.py b/posthog/api/csp_reporting.pyindex 3bff074ca253..8e25bf82b4b4 100644--- a/posthog/api/csp_reporting.py+++ b/posthog/api/csp_reporting.py@@ -1,4 +1,7 @@-import openai+from typing import cast++import posthoganalytics+from posthoganalytics.ai.openai import OpenAIfrom rest_framework import request, response, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticated@@ -6,6 +9,7 @@ from rest_framework.permissions import IsAuthenticatedfrom posthog.api.csp import CSP_REPORT_TYPES_MAPPING_TABLEfrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models import Userprompt = r"""You are a security consultant that explains CSP violation reports.@@ -48,11 +52,19 @@ class CSPReportingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if not properties:return response.Response({"error": "properties is required"}, status=400)- llm_response = openai.chat.completions.create(+ user = cast(User, request.user)+ llm_response = OpenAI(posthog_client=posthoganalytics.default_client).chat.completions.create( # type: ignore[call-overload]model="gpt-4.1-2025-04-14",temperature=0.1, # Using 0.1 to reduce hallucinations, but >0 to allow for some creativitymessages=[{"role": "system", "content": prompt}, {"role": "user", "content": properties}],user="ph/csp/explain",+ posthog_privacy_mode=True,+ posthog_distinct_id=user.distinct_id or str(user.id),+ posthog_properties={+ "ai_product": "csp_reporting",+ "ai_feature": "explain-violation",+ "team_id": self.team_id,+ },stream=False,)diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex edfc266cb5cc..f3d8ac3e7aa9 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -231,6 +231,7 @@ class SetupWizardViewSet(viewsets.ViewSet):"project_api_key": "mock-project-api-key","host": "http://localhost:8010","user_distinct_id": "mock-user-id",+ "team_id": 1,}cache.set(key, wizard_data, SETUP_WIZARD_CACHE_TIMEOUT)@@ -241,11 +242,13 @@ class SetupWizardViewSet(viewsets.ViewSet):raise AuthenticationFailed("Setup wizard not authenticated. Please login first")distinct_id = wizard_data.get("user_distinct_id")+ team_id = wizard_data.get("team_id")trace_id = trace_id or hashlib.sha256(hash.encode()).hexdigest()else:- result = OAuthAccessTokenAuthentication().authenticate(request)+ authenticator = OAuthAccessTokenAuthentication()+ result = authenticator.authenticate(request)if not result:raise AuthenticationFailed("Invalid access token.")@@ -256,6 +259,8 @@ class SetupWizardViewSet(viewsets.ViewSet):raise AuthenticationFailed("Invalid access token.")distinct_id = user.distinct_id+ scoped_team_ids = authenticator.access_token.scoped_teams or []+ team_id = scoped_team_ids[0] if len(scoped_team_ids) == 1 else Nonetrace_id = request.headers.get("X-PostHog-Trace-Id") or hashlib.sha256(distinct_id.encode()).hexdigest()@@ -304,6 +309,7 @@ class SetupWizardViewSet(viewsets.ViewSet):posthog_properties={"ai_product": "wizard","ai_feature": "query",+ "team_id": team_id,},)@@ -344,6 +350,7 @@ class SetupWizardViewSet(viewsets.ViewSet):posthog_properties={"ai_product": "wizard","ai_feature": "query",+ "team_id": team_id,},temperature=1.0,)@@ -412,6 +419,7 @@ class SetupWizardViewSet(viewsets.ViewSet):)project_api_token = project.passthrough_team.api_token+ team_id = project.passthrough_team.idexcept Project.DoesNotExist as e:capture_exception(e,@@ -428,6 +436,7 @@ class SetupWizardViewSet(viewsets.ViewSet):"project_api_key": project_api_token,"host": get_api_host(),"user_distinct_id": request.user.distinct_id,+ "team_id": team_id,}cache.set(cache_key, wizard_data, SETUP_WIZARD_CACHE_TIMEOUT)diff --git a/posthog/api/wizard/test/test_http.py b/posthog/api/wizard/test/test_http.pyindex ce3b031e91e0..4f69e5335a74 100644--- a/posthog/api/wizard/test/test_http.py+++ b/posthog/api/wizard/test/test_http.py@@ -25,7 +25,9 @@ class SetupWizardTests(APIBaseTest):self.hash = "testhash"self.cache_key = f"{SETUP_WIZARD_CACHE_PREFIX}{self.hash}"cache.set(- self.cache_key, {"project_api_key": "test-key", "host": "http://localhost:8010"}, SETUP_WIZARD_CACHE_TIMEOUT+ self.cache_key,+ {"project_api_key": "test-key", "host": "http://localhost:8010", "team_id": self.team.id},+ SETUP_WIZARD_CACHE_TIMEOUT,)def test_initialize_creates_hash(self):@@ -118,6 +120,39 @@ class SetupWizardTests(APIBaseTest):)assert response.status_code == status.HTTP_200_OKassert response.json() == {"data": {"foo": "bar"}}+ assert mock_openai_instance.chat.completions.create.call_args.kwargs["posthog_properties"] == {+ "ai_product": "wizard",+ "ai_feature": "query",+ "team_id": self.team.id,+ }++ @patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())+ @patch("posthog.api.wizard.http.OAuthAccessTokenAuthentication")+ @patch("posthog.api.wizard.http.OpenAI")+ def test_query_endpoint_uses_oauth_scoped_team(self, mock_openai, mock_authentication):+ mock_openai_instance = mock_openai.return_value+ mock_openai_instance.chat.completions.create.return_value = MagicMock(+ choices=[MagicMock(message=MagicMock(content=json.dumps({"foo": "bar"})))]+ )+ mock_authenticator = mock_authentication.return_value+ mock_authenticator.authenticate.return_value = (self.user, None)+ mock_authenticator.access_token.scoped_teams = [self.team.id]++ response = self.client.post(+ self.query_url,+ data=json.dumps(+ {"message": "test", "json_schema": {"type": "object", "properties": {"name": {"type": "number"}}}}+ ),+ content_type="application/json",+ headers={"authorization": "Bearer pha_test"},+ )++ assert response.status_code == status.HTTP_200_OK+ assert mock_openai_instance.chat.completions.create.call_args.kwargs["posthog_properties"] == {+ "ai_product": "wizard",+ "ai_feature": "query",+ "team_id": self.team.id,+ }@patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())@patch("posthog.api.wizard.http.OpenAI")@@ -193,7 +228,11 @@ class SetupWizardTests(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"data": {"result": "gemini_success"}}- mock_client_instance.models.generate_content.assert_called_once()+ assert mock_client_instance.models.generate_content.call_args.kwargs["posthog_properties"] == {+ "ai_product": "wizard",+ "ai_feature": "query",+ "team_id": self.team.id,+ }def test_query_endpoint_rejects_invalid_model(self):response = self.client.post(@@ -247,6 +286,7 @@ class SetupWizardTests(APIBaseTest):assert cached_data["project_api_key"] == "mock-project-api-key"assert cached_data["host"] == "http://localhost:8010"assert cached_data["user_distinct_id"] == "mock-user-id"+ assert cached_data["team_id"] == 1@patch("django.conf.settings.DEBUG", True)@patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())@@ -283,6 +323,7 @@ class SetupWizardTests(APIBaseTest):assert cached_data["project_api_key"] == "mock-project-api-key"assert cached_data["host"] == "http://localhost:8010"assert cached_data["user_distinct_id"] == "mock-user-id"+ assert cached_data["team_id"] == 1@patch("django.conf.settings.DEBUG", False)@patch("posthog.api.wizard.http.posthoganalytics.default_client", MagicMock())@@ -397,6 +438,7 @@ class SetupWizardTests(APIBaseTest):self.assertEqual(updated_data["project_api_key"], self.team.api_token)self.assertEqual(updated_data["host"], get_api_host())self.assertEqual(updated_data["user_distinct_id"], self.user.distinct_id)+ self.assertEqual(updated_data["team_id"], self.team.id)@override_settings(CACHES={diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex 2dd5779a242f..35d29d830de3 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -1744,6 +1744,7 @@ class SessionRecordingViewSet(posthog_properties={"ai_product": "session_replay","ai_feature": "ai_regex",+ "team_id": self.team.id,},)diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 8c7eeb18af49..4a2aaa5f1f4e 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -309,7 +309,16 @@ def call_llm_judge(client = Client(provider_key=provider_key,config=config,- capture_analytics=False,+ privacy_mode=True,+ distinct_id=f"team-{team_id}",+ properties={+ "ai_product": "aio_evaluations",+ "ai_feature": "llm-judge",+ "team_id": team_id,+ "evaluation_id": evaluation["id"],+ "$ai_billable": not is_byok,+ "is_byok": is_byok,+ },)try:diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex f604d703c06a..d19a8aa993d8 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -240,7 +240,16 @@ Output: {output_data}"""client = Client(provider_key=provider_key,config=config,- capture_analytics=False,+ privacy_mode=True,+ distinct_id=f"team-{team_id}",+ properties={+ "ai_product": "aio_evaluations",+ "ai_feature": "tagger",+ "team_id": team_id,+ "tagger_id": tagger["id"],+ "$ai_billable": not is_byok,+ "is_byok": is_byok,+ },)try:diff --git a/products/ai_observability/backend/llm/client.py b/products/ai_observability/backend/llm/client.pyindex 2d1e5643ebab..8e496868a2cf 100644--- a/products/ai_observability/backend/llm/client.py+++ b/products/ai_observability/backend/llm/client.py@@ -34,6 +34,7 @@ class Client:properties: dict[str, Any] | None = None,groups: dict[str, Any] | None = None,capture_analytics: bool = True,+ privacy_mode: bool = False,):self.provider_key = provider_keyself.config = config@@ -43,6 +44,7 @@ class Client:properties=properties,groups=groups,capture=capture_analytics,+ privacy_mode=privacy_mode,)def _get_api_key(self) -> str | None:diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.pyindex 42ee834db1fd..1ee15d4807da 100644--- a/products/ai_observability/backend/llm/providers/anthropic.py+++ b/products/ai_observability/backend/llm/providers/anthropic.py@@ -418,6 +418,7 @@ class AnthropicAdapter:"posthog_trace_id": analytics.trace_id or str(uuid.uuid4()),"posthog_properties": analytics.properties or {},"posthog_groups": analytics.groups or {},+ "posthog_privacy_mode": analytics.privacy_mode,}return {}diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.pyindex 31635684bf0c..1e379b9564fd 100644--- a/products/ai_observability/backend/llm/providers/gemini.py+++ b/products/ai_observability/backend/llm/providers/gemini.py@@ -197,6 +197,7 @@ class GeminiAdapter:"posthog_trace_id": analytics.trace_id or str(uuid.uuid4()),"posthog_properties": analytics.properties or {},"posthog_groups": analytics.groups or {},+ "posthog_privacy_mode": analytics.privacy_mode,}try:diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.pyindex 15fcfb30b5ba..e081fba6de85 100644--- a/products/ai_observability/backend/llm/providers/openai.py+++ b/products/ai_observability/backend/llm/providers/openai.py@@ -446,6 +446,7 @@ Return ONLY the JSON object, no other text or markdown formatting.""""posthog_trace_id": analytics.trace_id or str(uuid.uuid4()),"posthog_properties": analytics.properties or {},"posthog_groups": analytics.groups or {},+ "posthog_privacy_mode": analytics.privacy_mode,}return {}diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.pyindex 5b7d83a6a39a..975e2a752803 100644--- a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py+++ b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py@@ -68,7 +68,7 @@ class TestBuildAnalyticsKwargs:def test_wrapped_clients_get_analytics_kwargs_when_capture_enabled(self, _name, client_cls):adapter = OpenAIAdapter()client = MagicMock(spec=client_cls)- analytics = AnalyticsContext(distinct_id="user-1", trace_id="trace-1", capture=True)+ analytics = AnalyticsContext(distinct_id="user-1", trace_id="trace-1", capture=True, privacy_mode=True)kwargs = adapter._build_analytics_kwargs(analytics, client)@@ -77,6 +77,7 @@ class TestBuildAnalyticsKwargs:"posthog_trace_id": "trace-1","posthog_properties": {},"posthog_groups": {},+ "posthog_privacy_mode": True,}def test_capture_disabled_returns_empty_kwargs(self):diff --git a/products/ai_observability/backend/llm/types.py b/products/ai_observability/backend/llm/types.pyindex ef23452bdba7..e50d061d943e 100644--- a/products/ai_observability/backend/llm/types.py+++ b/products/ai_observability/backend/llm/types.py@@ -55,7 +55,7 @@ class StreamChunk:return f"data: {json.dumps({'type': self.type, **self.data})}\n\n"-@dataclass+@dataclass(frozen=False)class AnalyticsContext:"""Context for PostHog analytics tracking"""@@ -64,3 +64,4 @@ class AnalyticsContext:properties: dict[str, Any] | None = Nonegroups: dict[str, Any] | None = Nonecapture: bool = True+ privacy_mode: bool = Falsediff --git a/products/ai_observability/backend/summarization/llm/openai.py b/products/ai_observability/backend/summarization/llm/openai.pyindex 660e84f6413f..0f9f7e464b67 100644--- a/products/ai_observability/backend/summarization/llm/openai.py+++ b/products/ai_observability/backend/summarization/llm/openai.py@@ -7,7 +7,7 @@ import structlogfrom openai.types.chat import ChatCompletionMessageParamfrom rest_framework import exceptions-from posthog.llm.gateway_client import build_openai_client+from posthog.llm.gateway_client import build_openai_client, team_distinct_idfrom ..constants import SUMMARIZATION_TIMEOUTfrom ..models import OpenAIModel, SummarizationMode@@ -28,7 +28,13 @@ def summarize_with_openai(system_prompt = load_summarization_template(f"prompts/system_{mode}.djt", {})user_prompt = load_summarization_template("prompts/user.djt", {"text_repr": text_repr})- client = build_openai_client("llma_summarization", ai_product="aio_summarization")+ resolved_distinct_id = user_id or team_distinct_id(team_id)+ client = build_openai_client(+ "llma_summarization",+ ai_product="aio_summarization",+ properties={"team_id": str(team_id)},+ distinct_id=resolved_distinct_id,+ )messages: list[ChatCompletionMessageParam] = [{"role": "system", "content": system_prompt},@@ -39,7 +45,7 @@ def summarize_with_openai(response = client.chat.completions.create(model=str(model),messages=messages,- user=user_id or f"team-{team_id}",+ user=resolved_distinct_id,timeout=SUMMARIZATION_TIMEOUT,response_format=cast(Any,diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.pyindex 8f4d3e8749ce..a7c4d3434032 100644--- a/products/ai_observability/backend/summarization/tests/test_providers.py+++ b/products/ai_observability/backend/summarization/tests/test_providers.py@@ -42,7 +42,12 @@ class TestSummarizeWithOpenAI:assert isinstance(result, SummarizationResponse)assert result.title == "Test Summary"- mock_get_client.assert_called_once_with("llma_summarization", ai_product="aio_summarization")+ mock_get_client.assert_called_once_with(+ "llma_summarization",+ ai_product="aio_summarization",+ properties={"team_id": "1"},+ distinct_id="team-1",+ )def test_empty_response_raises_validation_error(self):mock_response = MagicMock()diff --git a/products/logs/backend/presentation/views/explain.py b/products/logs/backend/presentation/views/explain.pyindex c4c8ef1edf13..a619c448b0a2 100644--- a/products/logs/backend/presentation/views/explain.py+++ b/products/logs/backend/presentation/views/explain.py@@ -16,9 +16,10 @@ from django.core.cache import cachefrom django.template import Context, Engineimport structlog+import posthoganalyticsfrom asgiref.sync import async_to_sync-from openai import AsyncOpenAIfrom openai.types.chat import ChatCompletionMessageParam+from posthoganalytics.ai.openai import AsyncOpenAIfrom pydantic import BaseModel, ConfigDict, Fieldfrom rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.request import Request@@ -222,7 +223,7 @@ async def explain_log_with_openai(log_data: dict, team_id: int) -> LogExplanatiosystem_prompt = load_prompt_template("explain_system.djt", {})user_prompt = load_prompt_template("explain_user.djt", log_data)- client = AsyncOpenAI(timeout=EXPLAIN_TIMEOUT)+ client = AsyncOpenAI(posthog_client=posthoganalytics.default_client, timeout=EXPLAIN_TIMEOUT)messages: list[ChatCompletionMessageParam] = [{"role": "system", "content": system_prompt},@@ -230,7 +231,7 @@ async def explain_log_with_openai(log_data: dict, team_id: int) -> LogExplanatio]try:- response = await client.chat.completions.create(+ response = await client.chat.completions.create( # type: ignore[call-overload]model="gpt-4.1",messages=messages,response_format=cast(@@ -244,6 +245,13 @@ async def explain_log_with_openai(log_data: dict, team_id: int) -> LogExplanatio},},),+ posthog_privacy_mode=True,+ posthog_distinct_id=f"team-{team_id}",+ posthog_properties={+ "ai_product": "logs",+ "ai_feature": "explain-log",+ "team_id": team_id,+ },)content = response.choices[0].message.contentdiff --git a/products/logs/backend/test/test_explain.py b/products/logs/backend/test/test_explain.pyindex 9e1e48114516..ccb2156fcd24 100644--- a/products/logs/backend/test/test_explain.py+++ b/products/logs/backend/test/test_explain.py@@ -100,6 +100,13 @@ class TestExplainLogWithOpenAI:assert result.severity_assessment == "error"assert len(result.probable_causes) == 1assert result.probable_causes[0].confidence == "high"+ assert mock_client.chat.completions.create.call_args.kwargs["posthog_properties"] == {+ "ai_product": "logs",+ "ai_feature": "explain-log",+ "team_id": 1,+ }+ assert mock_client.chat.completions.create.call_args.kwargs["posthog_distinct_id"] == "team-1"+ assert mock_client.chat.completions.create.call_args.kwargs["posthog_privacy_mode"] is True@pytest.mark.asyncioasync def test_empty_response_raises_validation_error(self, sample_log_data):diff --git a/products/posthog_ai/eval_harness/scorers/tracing.py b/products/posthog_ai/eval_harness/scorers/tracing.pyindex a00fa80c38bb..7fb70304e9c2 100644--- a/products/posthog_ai/eval_harness/scorers/tracing.py+++ b/products/posthog_ai/eval_harness/scorers/tracing.py@@ -16,6 +16,8 @@ from contextvars import ContextVarfrom dataclasses import dataclassfrom typing import Any+from django.conf import settings+from posthoganalytics import Posthogfrom ..trace_events import DISTINCT_ID@@ -45,6 +47,7 @@ def _build_posthog_kwargs() -> dict[str, Any]:"$ai_parent_id": trace_id,"$ai_span_name": "Scorer","ai_product": "evals",+ "team_id": settings.LLM_ANALYTICS_INTERNAL_TEAM_ID,"$ai_experiment_id": ctx.get("experiment_id", ""),"$ai_experiment_name": ctx.get("experiment_name", ""),},@@ -205,6 +208,7 @@ class TracedScorer(AsyncOnlyScorerMixin, Scorer):**metadata,},"ai_product": "evals",+ "team_id": settings.LLM_ANALYTICS_INTERNAL_TEAM_ID,"$ai_experiment_id": self._eval_metadata.get("experiment_id", ""),"$ai_experiment_name": self._eval_metadata.get("experiment_name", ""),},diff --git a/products/replay_vision/backend/feedback_themes.py b/products/replay_vision/backend/feedback_themes.pyindex 65f369c6ffa9..df6c4ef74e99 100644--- a/products/replay_vision/backend/feedback_themes.py+++ b/products/replay_vision/backend/feedback_themes.py@@ -116,7 +116,11 @@ def _summarize(*, comments: list[str], team_id: int, distinct_id: str) -> _LlmFeconfig=config,posthog_distinct_id=distinct_id,posthog_trace_id=str(uuid.uuid4()),- posthog_properties={"ai_product": "replay_vision", "feature": "feedback_themes"},+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "feedback_themes",+ "team_id": team_id,+ },posthog_groups={"project": str(team_id)},)except Exception as e:diff --git a/products/replay_vision/backend/prompt_suggestions.py b/products/replay_vision/backend/prompt_suggestions.pyindex e5156dcabb33..521be831b732 100644--- a/products/replay_vision/backend/prompt_suggestions.py+++ b/products/replay_vision/backend/prompt_suggestions.py@@ -273,7 +273,11 @@ def _generate(config=config,posthog_distinct_id=distinct_id,posthog_trace_id=str(uuid.uuid4()),- posthog_properties={"ai_product": "replay_vision", "feature": "suggest_scanner_prompt"},+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "suggest_scanner_prompt",+ "team_id": team_id,+ },posthog_groups={"project": str(team_id)},)except Exception as e:@@ -404,7 +408,11 @@ def _model_call(config=config,posthog_distinct_id=distinct_id,posthog_trace_id=str(uuid.uuid4()),- posthog_properties={"ai_product": "replay_vision", "feature": "suggest_scanner_prompt_agentic"},+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "suggest_scanner_prompt_agentic",+ "team_id": team_id,+ },posthog_groups={"project": str(team_id)},)diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex ba4a3a2d1c48..74873339d8f8 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -352,7 +352,11 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmDraftconfig=config,posthog_distinct_id=distinct_id,posthog_trace_id=str(uuid.uuid4()),- posthog_properties={"ai_product": "replay_vision", "feature": "draft_scanner_from_goal"},+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "draft_scanner_from_goal",+ "team_id": team_id,+ },posthog_groups={"project": str(team_id)},)diff --git a/products/replay_vision/backend/tag_suggestions.py b/products/replay_vision/backend/tag_suggestions.pyindex 7972d18c4d97..1ef9c1596d66 100644--- a/products/replay_vision/backend/tag_suggestions.py+++ b/products/replay_vision/backend/tag_suggestions.py@@ -331,7 +331,11 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmSuggeconfig=config,posthog_distinct_id=distinct_id,posthog_trace_id=str(uuid.uuid4()),- posthog_properties={"ai_product": "replay_vision", "feature": "suggest_classifier_tags"},+ posthog_properties={+ "ai_product": "replay_vision",+ "feature": "suggest_classifier_tags",+ "team_id": team_id,+ },posthog_groups={"project": str(team_id)},)except Exception as e:diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 81b957fbefe5..3be4031eb736 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -366,6 +366,7 @@ async def _run_mission("ai_product": "replay_vision","feature": "scanner","scanner_type": snapshot.scanner_type.value,+ "team_id": team_id,},)cache_client = GoogleGenAIClient(api_key=api_key)diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex 9addb2721acb..41f46c2add2f 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -1,6 +1,7 @@from typing import Any, castimport pytest+from unittest.mock import AsyncMock, MagicMock, patchimport httpxfrom google.genai.errors import APIError@@ -8,6 +9,7 @@ from pydantic import BaseModelfrom products.replay_vision.backend.temporal.activities.call_scanner_provider import (_maybe_create_video_cache,+ _run_mission,_run_mission_attempts,_run_pass,_run_steps,@@ -79,6 +81,51 @@ async def _run(client: _FakeClient, steps: list[MissionStep], dispatch: Any = la)+async def test_scanner_generations_include_team_attribution() -> None:+ scanner = MagicMock()+ scanner.mission_steps.return_value = []+ snapshot = MagicMock()+ snapshot.scanner_type.value = "monitor"+ snapshot.model = "gemini-3-flash-preview"+ snapshot.provider = "gemini"++ with (+ patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider.genai.AsyncClient"+ ) as client_cls,+ patch("products.replay_vision.backend.temporal.activities.call_scanner_provider.GoogleGenAIClient"),+ patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._maybe_create_video_cache",+ new=AsyncMock(return_value=None),+ ),+ patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._run_mission_attempts",+ new=AsyncMock(return_value={}),+ ),+ patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider.build_events_index",+ return_value={},+ ),+ ):+ await _run_mission(+ scanner=scanner,+ snapshot=snapshot,+ video_part=_VIDEO,+ preamble_text="PRE",+ team_id=42,+ llm_inputs=MagicMock(),+ trace_id="trace-1",+ )++ assert client_cls.call_args.kwargs["posthog_properties"] == {+ "ai_product": "replay_vision",+ "feature": "scanner",+ "scanner_type": "monitor",+ "team_id": 42,+ }++@pytest.mark.asyncioasync def test_runs_each_step_and_keys_outputs_by_name() -> None:steps = [diff --git a/products/user_interviews/backend/max_tools.py b/products/user_interviews/backend/max_tools.pyindex a40b0f5ad84b..3147dfcd2353 100644--- a/products/user_interviews/backend/max_tools.py+++ b/products/user_interviews/backend/max_tools.py@@ -4,7 +4,8 @@ from typing import Anyfrom django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationError-from openai import OpenAI+import posthoganalytics+from posthoganalytics.ai.openai import OpenAIfrom pydantic import BaseModel, ConfigDict, Fieldfrom rest_framework.serializers import ValidationError as DRFValidationError@@ -56,8 +57,17 @@ class AnalyzeUserInterviewsTool(MaxTool):interview_summaries_text = "\n\n".join(interview_summaries)# Use GPT to analyze the summaries- analysis_response = OpenAI(base_url=settings.OPENAI_BASE_URL).responses.create(+ analysis_response = OpenAI(+ posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL+ ).responses.create( # type: ignore[call-overload]model="gpt-4.1-mini",+ posthog_privacy_mode=True,+ posthog_distinct_id=self._user.distinct_id,+ posthog_properties={+ "ai_product": "user_interviews",+ "ai_feature": "analyze-interviews",+ "team_id": self._team.id,+ },input=[{"role": "system",diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.pyindex a049434594f4..3ab13baf0d37 100644--- a/products/user_interviews/backend/presentation/views.py+++ b/products/user_interviews/backend/presentation/views.py@@ -160,7 +160,13 @@ class UserInterviewSerializer(serializers.ModelSerializer):).responses.create( # type: ignoremodel="gpt-4.1-mini",posthog_trace_id=self._ai_trace_id,+ posthog_privacy_mode=True,posthog_distinct_id=self.context["request"].user.distinct_id,+ posthog_properties={+ "ai_product": "user_interviews",+ "ai_feature": "map-speakers",+ "team_id": self.context["request"].user.current_team_id,+ },input=[{"role": "system",@@ -237,7 +243,13 @@ Map the speakers in the following transcript:summary_response = OpenAI(posthog_client=posthoganalytics.default_client).responses.create( # type: ignoremodel="gpt-4.1-mini",posthog_trace_id=self._ai_trace_id,+ posthog_privacy_mode=True,posthog_distinct_id=self.context["request"].user.distinct_id,+ posthog_properties={+ "ai_product": "user_interviews",+ "ai_feature": "summarize-transcript",+ "team_id": self.context["request"].user.current_team_id,+ },input=[{"role": "system",