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.

fix(aio): emit one prompt fetched event per labeled list request (#103955)

Juraj Majerik7c33928ad098
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 37ff2e90cf76..4763dd8da9c2 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -16,7 +16,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
-from posthog.api.capture import capture_batch_internal, capture_internal
+from posthog.api.capture import capture_internal
from posthog.api.llm_prompt_serializers import (
ALLOWED_LIST_ORDERINGS,
LLMPromptDuplicateSerializer,
@@ -258,33 +258,28 @@ 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:
+ def _track_labeled_list_fetch(self, prompts: Sequence[LLMPrompt], label: str) -> 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 = {
+ "prompt_fetch_path": "list",
+ "prompt_label": label,
+ "prompt_count": len(prompts),
+ }
+ if not settings.TEST:
try:
- capture_batch_internal(
- events=[
- {
- "event": PROMPT_FETCHED_EVENT,
- "distinct_id": str(self.team.uuid),
- "properties": properties,
- }
- for properties in properties_per_prompt
- ],
+ capture_internal(
token=self.team.api_token,
+ event_name=PROMPT_FETCHED_EVENT,
event_source=PROMPT_FETCHED_EVENT_SOURCE,
+ distinct_id=str(self.team.uuid),
+ timestamp=None,
+ properties=properties,
)
except Exception as err:
capture_exception(err)
- for properties in properties_per_prompt:
- report_team_action(self.team, "llma prompt fetched", properties)
+ 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)
@@ -741,18 +736,6 @@ 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 = (
@@ -778,10 +761,8 @@ class LLMPromptViewSet(
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)
+ # The unlabeled list backs the prompts UI page and stays untracked.
+ self._track_labeled_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.py
index 10c3bd7227f8..905c238e3d1d 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -1461,33 +1461,39 @@ class TestLLMPromptLabelsAPI(APIBaseTest):
assert results[0]["latest_version"] == 2
assert results[0]["prompt"] == "Prompt content"
+ @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_returned_prompt(self, mock_report: Any) -> None:
+ def test_list_with_label_reports_one_fetch_per_request(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_CREATED
assert 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")
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.
+ expected_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 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"),
- ]
+ assert fetch_properties == [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.
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()
def test_archive_prompt_deletes_its_labels(self):
self.create_prompt_version(version=1)