: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 labeled list calls (#98183)
Juraj Majerik7d776ae0f691
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex 808e1153daec..3bfe6f8fdb51 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -1,4 +1,5 @@import json+from collections.abc import Sequencefrom typing import Any, castfrom uuid import UUID@@ -14,7 +15,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer-from posthog.api.capture import capture_internal+from posthog.api.capture import capture_batch_internal, capture_internalfrom posthog.api.llm_prompt_serializers import (ALLOWED_LIST_ORDERINGS,LLMPromptDuplicateSerializer,@@ -191,10 +192,10 @@ class LLMPromptViewSet(prompt["config"] = prompt.get("config")return prompt- def _track_prompt_fetch(self, prompt: dict[str, Any]) -> None:+ def _prompt_fetch_properties(self, prompt: dict[str, Any], fetch_path: str) -> dict[str, Any]:# prompt_label + prompt_version together answer "what was the production label# actually serving at time X" from the event stream alone.- properties = {+ return {"prompt_id": prompt["id"],"prompt_name": prompt["name"],"prompt_version": prompt["version"],@@ -202,7 +203,11 @@ class LLMPromptViewSet("prompt_is_latest": prompt["is_latest"],"prompt_first_version_created_at": prompt["first_version_created_at"],"prompt_has_config": prompt.get("config") is not None,+ "prompt_fetch_path": fetch_path,}++ def _track_prompt_fetch(self, prompt: dict[str, Any]) -> None:+ properties = self._prompt_fetch_properties(prompt, fetch_path="by_name")if not settings.TEST:try:capture_internal(@@ -218,6 +223,34 @@ class LLMPromptViewSet(report_team_action(self.team, "llma prompt fetched", properties)+ def _track_labeled_list_fetches(self, prompts: Sequence[LLMPrompt], label: str) -> None:+ # One batch call, not one capture_internal per prompt: capture_internal is a+ # synchronous HTTP request, so per-prompt calls would multiply request latency+ # by the page size.+ properties_per_prompt = [+ self._prompt_fetch_properties(self._labeled_list_fetch_payload(prompt, label), fetch_path="list")+ for prompt in prompts+ ]+ if not settings.TEST and properties_per_prompt:+ try:+ capture_batch_internal(+ events=[+ {+ "event": PROMPT_FETCHED_EVENT,+ "distinct_id": str(self.team.uuid),+ "properties": properties,+ }+ for properties in properties_per_prompt+ ],+ token=self.team.api_token,+ event_source=PROMPT_FETCHED_EVENT_SOURCE,+ )+ except Exception as err:+ capture_exception(err)++ for properties in properties_per_prompt:+ report_team_action(self.team, "llma prompt fetched", properties)+def _get_list_params(self, request: Request) -> dict[str, Any]:serializer = LLMPromptListQuerySerializer(data=request.query_params)serializer.is_valid(raise_exception=True)@@ -613,6 +646,18 @@ class LLMPromptViewSet()return Response(status=status.HTTP_204_NO_CONTENT)+ def _labeled_list_fetch_payload(self, prompt: LLMPrompt, label: str) -> dict[str, Any]:+ first_version_created_at = getattr(prompt, "first_version_created_at", None) or prompt.created_at+ return {+ "id": str(prompt.id),+ "name": prompt.name,+ "version": prompt.version,+ "label": label,+ "is_latest": prompt.is_latest,+ "first_version_created_at": first_version_created_at.isoformat().replace("+00:00", "Z"),+ "config": prompt.config,+ }+def _get_prompt_labels_map(self, prompt_names: list[str]) -> dict[str, list[dict[str, Any]]]:labels_map: dict[str, list[dict[str, Any]]] = {}labels = (@@ -636,6 +681,13 @@ class LLMPromptViewSet(context["prompt_labels_by_name"] = self._get_prompt_labels_map([prompt.name for prompt in prompts])serializer = LLMPromptListSerializer(prompts, many=True, context=context)+ label = self._get_list_params(request).get("label")+ if label:+ # Each prompt served through a labeled list counts as one fetch, matching+ # get_by_name, so usage counts survive a caller migrating from per-name+ # calls. The unlabeled list backs the prompts UI page and stays untracked.+ self._track_labeled_list_fetches(prompts, label)+if page is not None:return self.get_paginated_response(serializer.data)return Response({"count": len(serializer.data), "results": serializer.data})diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 0218c27982f5..c3f7ad03a371 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -1459,6 +1459,34 @@ class TestLLMPromptLabelsAPI(APIBaseTest):assert results[0]["latest_version"] == 2assert results[0]["prompt"] == "Prompt content"+ @patch("posthog.api.llm_prompt.report_team_action")+ def test_list_with_label_reports_one_fetch_per_returned_prompt(self, mock_report: 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_CREATED+ assert self._set_label("prompt-b", "production", 1).status_code == status.HTTP_201_CREATED+ mock_report.reset_mock()++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production")++ assert response.status_code == status.HTTP_200_OK+ fetch_properties = [+ call.args[2] for call in mock_report.call_args_list if call.args[1] == "llma prompt fetched"+ ]+ assert sorted(+ (p["prompt_name"], p["prompt_version"], p["prompt_label"], p["prompt_is_latest"], p["prompt_fetch_path"])+ for p in fetch_properties+ ) == [+ ("prompt-a", 1, "production", False, "list"),+ ("prompt-b", 1, "production", True, "list"),+ ]++ # The unlabeled list backs the prompts UI page and must not count as fetches.+ mock_report.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)+def test_archive_prompt_deletes_its_labels(self):self.create_prompt_version(version=1)assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED