: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
feat(aio): report prompt fetches on unlabeled list calls (#103978)
Juraj Majerik1a3b860c5c60
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex 4763dd8da9c2..5707f9e771c1 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -60,6 +60,7 @@ from posthog.api.services.llm_prompt import (set_prompt_label,)from posthog.auth import (+ DelegatedOAuthAccessTokenAuthentication,JwtAuthentication,OAuthAccessTokenAuthentication,PersonalAPIKeyAuthentication,@@ -142,6 +143,18 @@ class LLMPromptViewSet(return ["llm_prompt:write"] if request.method == "PATCH" else ["llm_prompt:read"]return None+ def _is_browser_session(self, request: Request) -> bool:+ # A delegated OAuth token is a service acting for a user, not the user's+ # browser, and its authenticator subclasses the OAuth one, so exclude it first.+ if isinstance(request.successful_authenticator, DelegatedOAuthAccessTokenAuthentication):+ return False+ # A session cookie means a browser, and so does an OAuth token, which the app+ # frontend uses when Django does not serve it. OAuth also carries third-party+ # API clients; missing their unlabeled list reads costs less than counting+ # every prompts page view as a fetch. A JWT is a background job impersonating+ # a user, which reads prompts like any other API caller.+ return isinstance(request.successful_authenticator, SessionAuthentication | OAuthAccessTokenAuthentication)+def _ensure_web_authenticated(self, request: Request) -> Response | None:if not isinstance(request.successful_authenticator,@@ -258,7 +271,7 @@ class LLMPromptViewSet(report_team_action(self.team, "llma prompt fetched", properties)- def _track_labeled_list_fetch(self, prompts: Sequence[LLMPrompt], label: str) -> None:+ def _track_list_fetch(self, prompts: Sequence[LLMPrompt], label: str | None) -> None:# One event per request, not per prompt: the event is billed into the calling# team's own project, so a page of N prompts would bill N events per call.properties = {@@ -760,9 +773,11 @@ class LLMPromptViewSet(serializer = LLMPromptListSerializer(prompts, many=True, context=context)label = self._get_list_params(request).get("label")- if label:- # The unlabeled list backs the prompts UI page and stays untracked.- self._track_labeled_list_fetch(prompts, label)+ if label or not self._is_browser_session(request):+ # The unlabeled list also backs the prompts UI page, where reading the+ # page is not a prompt fetch. The browser session separates a prompt+ # served to an application from someone looking at the list.+ self._track_list_fetch(prompts, label)if page is not None:return self.get_paginated_response(serializer.data)diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 905c238e3d1d..72803b5ffe65 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom typing import Anyfrom posthog.test.base import APIBaseTest@@ -6,6 +7,7 @@ from unittest.mock import patchfrom django.db import connectionfrom django.test import SimpleTestCase, override_settingsfrom django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status@@ -21,7 +23,11 @@ from posthog.api.llm_prompt_serializers import (validate_prompt_label_name_value,)from posthog.api.services.llm_prompt import MAX_PROMPT_VERSION+from posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.models import PersonalAPIKeyfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottlefrom posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache@@ -1464,36 +1470,97 @@ class TestLLMPromptLabelsAPI(APIBaseTest):@override_settings(TEST=False)@patch("posthog.api.llm_prompt.capture_internal")@patch("posthog.api.llm_prompt.report_team_action")- def test_list_with_label_reports_one_fetch_per_request(self, mock_report: Any, mock_capture: Any) -> None:+ def test_list_reports_one_fetch_per_request_unless_the_caller_is_the_ui(+ self, mock_report: Any, mock_capture: Any+ ) -> None:self.create_prompt_version(name="prompt-a", version=1, is_latest=False)self.create_prompt_version(name="prompt-a", version=2)self.create_prompt_version(name="prompt-b", version=1)assert self._set_label("prompt-a", "production", 1).status_code == status.HTTP_201_CREATEDassert self._set_label("prompt-b", "production", 1).status_code == status.HTTP_201_CREATED- mock_report.reset_mock()- mock_capture.reset_mock()- response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production")+ def fetch_events() -> list[dict[str, Any]]:+ return [call.args[2] for call in mock_report.call_args_list if call.args[1] == "llma prompt fetched"]- assert response.status_code == status.HTTP_200_OK# One event per request, never one per prompt: per-prompt events bill a page# of N prompts as N events into the calling team's project.+ mock_report.reset_mock()+ mock_capture.reset_mock()+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production")+ assert response.status_code == status.HTTP_200_OKexpected_properties = {"prompt_fetch_path": "list", "prompt_label": "production", "prompt_count": 2}- fetch_properties = [- call.args[2] for call in mock_report.call_args_list if call.args[1] == "llma prompt fetched"- ]- assert fetch_properties == [expected_properties]+ assert fetch_events() == [expected_properties]mock_capture.assert_called_once()assert mock_capture.call_args.kwargs["event_name"] == "$llm_prompt_fetched"assert mock_capture.call_args.kwargs["distinct_id"] == str(self.team.uuid)assert mock_capture.call_args.kwargs["properties"] == expected_properties- # The unlabeled list backs the prompts UI page and must not count as fetches.+ # An unlabeled list serves every prompt's latest version, so an API client+ # fetching it counts.+ pat_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test", user=self.user, secure_value=hash_key_value(pat_value), scopes=["*"]+ )mock_report.reset_mock()- mock_capture.reset_mock()- assert self.client.get(f"/api/environments/{self.team.id}/llm_prompts/").status_code == status.HTTP_200_OK- assert not any(call.args[1] == "llma prompt fetched" for call in mock_report.call_args_list)- mock_capture.assert_not_called()+ response = self.client.get(+ f"/api/environments/{self.team.id}/llm_prompts/", headers={"authorization": f"Bearer {pat_value}"}+ )+ assert response.status_code == status.HTTP_200_OK+ assert fetch_events() == [{"prompt_fetch_path": "list", "prompt_label": None, "prompt_count": 2}]++ # A JWT is a background job impersonating a user, still an API caller.+ impersonation_token = encode_jwt(+ {"id": self.user.id}, timedelta(minutes=15), PosthogJwtAudience.IMPERSONATED_USER+ )+ mock_report.reset_mock()+ response = self.client.get(+ f"/api/environments/{self.team.id}/llm_prompts/",+ headers={"authorization": f"Bearer {impersonation_token}"},+ )+ assert response.status_code == status.HTTP_200_OK+ assert [event["prompt_count"] for event in fetch_events()] == [2]++ # The same unlabeled list backs the prompts UI page, where reading the page is+ # not a fetch. The page holds a session cookie, or an OAuth token when Django+ # does not serve the frontend.+ oauth_application = OAuthApplication.objects.create(+ name="Test OAuth App",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ organization=self.organization,+ user=self.user,+ )+ oauth_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=oauth_application,+ token="pha_test_oauth_list_token",+ expires=timezone.now() + timedelta(hours=1),+ scope="llm_prompt:read",+ )+ for headers in ({}, {"authorization": f"Bearer {oauth_token.token}"}):+ mock_report.reset_mock()+ mock_capture.reset_mock()+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/", headers=headers)+ assert response.status_code == status.HTTP_200_OK+ assert fetch_events() == []+ mock_capture.assert_not_called()++ # A delegated OAuth token is a service acting for a user, not the user's+ # browser, so it counts as an API client.+ delegated_token = encode_jwt(+ {"id": self.user.id, "oauth_access_token_id": str(oauth_token.id)},+ timedelta(minutes=15),+ PosthogJwtAudience.DELEGATED_USER,+ )+ mock_report.reset_mock()+ response = self.client.get(+ f"/api/environments/{self.team.id}/llm_prompts/",+ headers={"authorization": f"Bearer {delegated_token}"},+ )+ assert response.status_code == status.HTTP_200_OK+ assert [event["prompt_count"] for event in fetch_events()] == [2]def test_archive_prompt_deletes_its_labels(self):self.create_prompt_version(version=1)