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.

feat(aio): fetch all prompts at a label in one request (#96137)

Juraj Majerikdb8e46540369
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 4a02e9df8fa5..808e1153daec 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -46,6 +46,7 @@ from posthog.api.services.llm_prompt import (
archive_prompt,
duplicate_prompt,
get_active_prompt_queryset,
+ get_labeled_prompts_queryset,
get_latest_prompts_queryset,
get_prompt_by_name_from_db,
get_prompt_labels,
@@ -225,7 +226,11 @@ class LLMPromptViewSet(
def _get_list_queryset(self, request: Request) -> QuerySet[LLMPrompt]:
params = self._get_list_params(request)
- queryset = get_latest_prompts_queryset(self.team).annotate(
+ label = params.get("label")
+ base_queryset = (
+ get_labeled_prompts_queryset(self.team, label) if label else get_latest_prompts_queryset(self.team)
+ )
+ queryset = base_queryset.annotate(
prompt_size_bytes=Func(
Cast("prompt", output_field=TextField()), function="OCTET_LENGTH", output_field=IntegerField()
),
diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.py
index 1913beed26b5..a3e2935e9bc3 100644
--- a/posthog/api/llm_prompt_serializers.py
+++ b/posthog/api/llm_prompt_serializers.py
@@ -174,6 +174,15 @@ class LLMPromptListQuerySerializer(serializers.Serializer):
required=False,
help_text="Filter prompts by the ID of the user who created them.",
)
+ label = serializers.CharField( # type: ignore[assignment]
+ required=False,
+ max_length=PROMPT_LABEL_NAME_MAX_LENGTH,
+ help_text=(
+ "Return each prompt at the version this label points to, e.g. 'production'. "
+ "Prompts that do not carry the label are omitted. "
+ "If omitted, the latest version of every prompt is returned."
+ ),
+ )
order_by = serializers.ChoiceField(
choices=list(ALLOWED_LIST_ORDERINGS),
required=False,
@@ -187,6 +196,9 @@ class LLMPromptListQuerySerializer(serializers.Serializer):
help_text=CONTENT_MODE_HELP,
)
+ def validate_label(self, value: str) -> str:
+ return validate_prompt_label_name_value(value)
+
class LLMPromptResolveQuerySerializer(LLMPromptFetchQuerySerializer):
version_id = serializers.UUIDField(
@@ -468,8 +480,9 @@ class LLMPromptListSerializer(LLMPromptSerializer):
@extend_schema_field(LLMPromptLabelSummarySerializer(many=True))
def get_all_labels(self, instance: LLMPrompt) -> list[dict[str, Any]]:
- # The list queryset holds latest-version rows, whose own `labels` miss labels
- # pointing at older versions; the viewset injects the full per-prompt map.
+ # A list row is one version (latest by default, the labeled one with ?label=),
+ # so its own `labels` miss labels pointing at the prompt's other versions;
+ # the viewset injects the full per-prompt map.
return self.context.get("prompt_labels_by_name", {}).get(instance.name, [])
def get_prompt_preview(self, instance: LLMPrompt) -> str:
diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.py
index 7bfeacd07712..7ca8fd193239 100644
--- a/posthog/api/services/llm_prompt.py
+++ b/posthog/api/services/llm_prompt.py
@@ -113,6 +113,13 @@ def get_latest_prompts_queryset(team: Team) -> QuerySet[LLMPrompt]:
return get_active_prompt_queryset(team).filter(is_latest=True)
+def get_labeled_prompts_queryset(team: Team, label_name: str) -> QuerySet[LLMPrompt]:
+ # Starts from the label rows, not from a WHERE on the latest queryset: a label
+ # usually points at a version that is no longer latest.
+ labeled_version_ids = LLMPromptLabel.objects.filter(team=team, name=label_name).values("prompt_id")
+ return get_active_prompt_queryset(team).filter(id__in=labeled_version_ids)
+
+
def get_prompt_by_name_from_db(
team: Team,
prompt_name: str,
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index 1cca939e6ca4..0218c27982f5 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -1303,6 +1303,13 @@ class TestLLMPromptListQuerySerializerValidationNoDB(SimpleTestCase):
assert not serializer.is_valid()
assert "order_by" in serializer.errors
+ def test_rejects_invalid_label(self) -> None:
+ # An invalid label must fail here rather than fall through to a latest-version
+ # response; the naming rules themselves are covered by the shared validator's tests.
+ serializer = LLMPromptListQuerySerializer(data={"label": "latest"})
+ assert not serializer.is_valid()
+ assert "label" in serializer.errors
+
class TestLLMPromptLabelsAPI(APIBaseTest):
def create_prompt_version(
@@ -1433,6 +1440,25 @@ class TestLLMPromptLabelsAPI(APIBaseTest):
label_queries = [q for q in queries.captured_queries if "llmpromptlabel" in q["sql"].lower()]
assert len(label_queries) == 2
+ def test_list_with_label_returns_labeled_versions_and_omits_unlabeled_prompts(self) -> 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)
+ self.create_prompt_version(name="prompt-c", 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
+ assert self._set_label("prompt-c", "staging", 1).status_code == status.HTTP_201_CREATED
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production&order_by=name")
+
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert [(entry["name"], entry["version"]) for entry in results] == [("prompt-a", 1), ("prompt-b", 1)]
+ # The labeled row keeps its version-history metadata even though it is not latest.
+ assert results[0]["is_latest"] is False
+ assert results[0]["latest_version"] == 2
+ assert results[0]["prompt"] == "Prompt content"
+
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
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 8a69d575fd09..b40845c6ba75 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -3563,6 +3563,12 @@ export type LlmPromptsListParams = {
* Filter prompts by the ID of the user who created them.
*/
created_by_id?: number
+ /**
+ * Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned.
+ * @minLength 1
+ * @maxLength 128
+ */
+ label?: string
/**
* Number of results to return per page.
*/
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index f25825bac1c9..9f5315970e1d 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -955,10 +955,11 @@ tools:
}
title: List prompts
description: >
- List all LLM prompts stored for the current team. Optionally filter by name. Returns paginated prompt
- summaries. By default, only prompt metadata is returned, not full prompt content. Every result also includes
- `outline`, a flat list of markdown headings parsed from the prompt — use it as a lightweight table of
- contents, and pair with `content=none` to keep responses small.
+ List all LLM prompts stored for the current team. Optionally filter by name. Pass `label` (e.g.
+ 'production') to get each prompt at the version that label currently points to; prompts without that label
+ are omitted. Returns paginated prompt summaries. By default, only prompt metadata is returned, not full
+ prompt content. Every result also includes `outline`, a flat list of markdown headings parsed from the
+ prompt — use it as a lightweight table of contents, and pair with `content=none` to keep responses small.
llma-prompt-resolve:
operation: llm_prompts_resolve_name_retrieve
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0e7114fa9dd1..d7d864a1be86 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6760,7 +6760,7 @@
}
},
"llma-prompt-list": {
- "description": "List all LLM prompts stored for the current team. Optionally filter by name. Returns paginated prompt summaries. By default, only prompt metadata is returned, not full prompt content. Every result also includes `outline`, a flat list of markdown headings parsed from the prompt — use it as a lightweight table of contents, and pair with `content=none` to keep responses small.",
+ "description": "List all LLM prompts stored for the current team. Optionally filter by name. Pass `label` (e.g. 'production') to get each prompt at the version that label currently points to; prompts without that label are omitted. Returns paginated prompt summaries. By default, only prompt metadata is returned, not full prompt content. Every result also includes `outline`, a flat list of markdown headings parsed from the prompt — use it as a lightweight table of contents, and pair with `content=none` to keep responses small.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "List prompts",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e308971b6cc9..bf0ea90246e6 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6999,7 +6999,7 @@
}
},
"llma-prompt-list": {
- "description": "List all LLM prompts stored for the current team. Optionally filter by name. Returns paginated prompt summaries. By default, only prompt metadata is returned, not full prompt content. Every result also includes `outline`, a flat list of markdown headings parsed from the prompt — use it as a lightweight table of contents, and pair with `content=none` to keep responses small.",
+ "description": "List all LLM prompts stored for the current team. Optionally filter by name. Pass `label` (e.g. 'production') to get each prompt at the version that label currently points to; prompts without that label are omitted. Returns paginated prompt summaries. By default, only prompt metadata is returned, not full prompt content. Every result also includes `outline`, a flat list of markdown headings parsed from the prompt — use it as a lightweight table of contents, and pair with `content=none` to keep responses small.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "List prompts",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 5cc8079e9152..f2f57eecd1af 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -881,6 +881,12 @@
"description": "Optional substring filter applied to prompt names and prompt content.",
"type": "string"
},
+ "label": {
+ "description": "Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned.",
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128
+ },
"content": {
"default": "none",
"description": "Controls how much prompt content is included in list results. 'full' includes the full prompt, 'preview' includes a short prompt_preview, and 'none' omits prompt content entirely.",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index cb9505dff196..67cf11734aba 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -98848,6 +98848,12 @@ export namespace Schemas {
* Filter prompts by the ID of the user who created them.
*/
created_by_id?: number;
+ /**
+ * Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned.
+ * @minLength 1
+ * @maxLength 128
+ */
+ label?: string;
/**
* Number of results to return per page.
*/
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 0dca0bc3d953..2cfff78ce33e 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -2086,6 +2086,8 @@ export const LlmPromptsListParams = () => zod.object({
})
export const llmPromptsListQueryContentDefault = `full`
+export const llmPromptsListQueryLabelMax = 128
+
export const llmPromptsListQueryOrderByDefault = `-created_at`
export const LlmPromptsListQueryParams = () => zod.object({
@@ -2096,6 +2098,14 @@ export const LlmPromptsListQueryParams = () => zod.object({
"Controls how much prompt content is included in the response. 'full' includes the full prompt, 'preview' includes a short prompt_preview, and 'none' omits prompt content entirely. The config field is only included with 'full'. The outline field is always included.\n\n\* `full` - full\n\* `preview` - preview\n\* `none` - none"
),
created_by_id: zod.number().optional().describe('Filter prompts by the ID of the user who created them.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(llmPromptsListQueryLabelMax)
+ .optional()
+ .describe(
+ "Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned."
+ ),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
order_by: zod
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 6db666f69c71..78a5bcf21ce1 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -199,6 +199,14 @@ export const ScoreDefinitionConfigSchema = z
export const PromptListInputSchema = z.object({
search: z.string().optional().describe('Optional substring filter applied to prompt names and prompt content.'),
+ label: z
+ .string()
+ .min(1)
+ .max(128)
+ .optional()
+ .describe(
+ "Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned."
+ ),
content: z
.enum(['full', 'preview', 'none'])
.default('none')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-list.json
index 667ba24a0976..324023fc253a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-list.json
@@ -7,6 +7,12 @@
"enum": ["full", "preview", "none"],
"type": "string"
},
+ "label": {
+ "description": "Return each prompt at the version this label points to, e.g. 'production'. Prompts that do not carry the label are omitted. If omitted, the latest version of every prompt is returned.",
+ "maxLength": 128,
+ "minLength": 1,
+ "type": "string"
+ },
"search": {
"description": "Optional substring filter applied to prompt names and prompt content.",
"type": "string"