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(prompts): resolve references in the labeled list fetch (#104359)

Juraj Majerik6b57048f325c
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 5707f9e771c1..5515748bc5a1 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -1,5 +1,4 @@
import json
-from collections.abc import Sequence
from typing import Any, cast
from uuid import UUID
@@ -8,6 +7,7 @@ from django.db import IntegrityError
from django.db.models import Func, IntegerField, Q, QuerySet, TextField
from django.db.models.functions import Cast
+import structlog
import posthoganalytics
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import mixins, serializers, status, viewsets
@@ -78,11 +78,14 @@ from products.ai_observability.backend.activity_logging import log_llm_prompt_ac
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outline
from products.ai_observability.backend.prompt_references import (
+ PROMPT_REFERENCE_REGEX,
PromptReferenceResolutionError,
assemble_prompt_payload,
get_active_references_to,
)
+logger = structlog.get_logger(__name__)
+
PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"
PROMPT_FETCHED_EVENT_SOURCE = "llm_prompt_management"
@@ -271,13 +274,68 @@ class LLMPromptViewSet(
report_team_action(self.team, "llma prompt fetched", properties)
- def _track_list_fetch(self, prompts: Sequence[LLMPrompt], label: str | None) -> None:
+ def _reference_resolution_error_response(self, err: PromptReferenceResolutionError) -> Response:
+ error_status: int = status.HTTP_409_CONFLICT
+ if err.unavailable:
+ error_status = status.HTTP_503_SERVICE_UNAVAILABLE
+ elif err.missing:
+ error_status = status.HTTP_404_NOT_FOUND
+ return Response({"detail": err.message, "reference_name": err.reference_name}, status=error_status)
+
+ def _resolve_labeled_list_items(self, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Splice references into labeled list rows, mirroring get_by_name.
+
+ An unresolvable reference fails the whole request with the same
+ status get_by_name uses. Serving the raw tag would leak it into the
+ caller's LLM, and omitting the row would silently shorten a page,
+ which a paginating client reads as the end of the results.
+ """
+
+ def has_tags(item: dict[str, Any]) -> bool:
+ return isinstance(item.get("prompt"), str) and bool(PROMPT_REFERENCE_REGEX.search(item["prompt"]))
+
+ # A tag-free row is trivially resolved: its raw and assembled content are
+ # identical, so it gets [] without consulting the flag. Null stays the
+ # marker for tags that were left in place.
+ for item in items:
+ if not has_tags(item):
+ item["resolved_references"] = []
+ if not any(has_tags(item) for item in items):
+ return items
+ if not prompt_partials_enabled(self.team):
+ return items
+ resolved_items: list[dict[str, Any]] = []
+ shared_memo: dict[tuple[str, str | None, str | None], tuple[str, int]] = {}
+ for item in items:
+ if not has_tags(item):
+ resolved_items.append(item)
+ continue
+ try:
+ assembled = assemble_prompt_payload(self.team, item, memoized=shared_memo)
+ except PromptReferenceResolutionError as err:
+ # The bulk response has no single subject, so the message names
+ # the prompt whose reference failed.
+ raise PromptReferenceResolutionError(
+ reference_name=err.reference_name,
+ message=f"Prompt '{item.get('name')}': {err.message}",
+ missing=err.missing,
+ unavailable=err.unavailable,
+ ) from err
+ # The outline is derived from content, so it must describe what
+ # this response returns. prompt_size_bytes stays the stored size:
+ # it backs the list ordering.
+ assembled["outline"] = get_prompt_outline(assembled.get("prompt"))
+ resolved_items.append(assembled)
+ return resolved_items
+
+ def _track_list_fetch(self, served_count: int, label: str | None, resolved_reference_count: int) -> 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),
+ "prompt_count": served_count,
+ "prompt_resolved_reference_count": resolved_reference_count,
}
if not settings.TEST:
try:
@@ -403,12 +461,7 @@ class LLMPromptViewSet(
try:
prompt = assemble_prompt_payload(self.team, prompt)
except PromptReferenceResolutionError as err:
- error_status: int = status.HTTP_409_CONFLICT
- if err.unavailable:
- error_status = status.HTTP_503_SERVICE_UNAVAILABLE
- elif err.missing:
- error_status = status.HTTP_404_NOT_FOUND
- return Response({"detail": err.message, "reference_name": err.reference_name}, status=error_status)
+ return self._reference_resolution_error_response(err)
self._track_prompt_fetch(prompt)
return Response(self._apply_content_mode(prompt, content_mode))
@@ -772,16 +825,25 @@ 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")
+ params = self._get_list_params(request)
+ label = params.get("label")
+ data = list(serializer.data)
+ if label is not None and params.get("content", "full") == "full" and cast(bool, params.get("resolve", True)):
+ try:
+ data = self._resolve_labeled_list_items(data)
+ except PromptReferenceResolutionError as err:
+ return self._reference_resolution_error_response(err)
+
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)
+ resolved_reference_count = sum(len(item.get("resolved_references") or []) for item in data)
+ self._track_list_fetch(len(data), label, resolved_reference_count)
if page is not None:
- return self.get_paginated_response(serializer.data)
- return Response({"count": len(serializer.data), "results": serializer.data})
+ return self.get_paginated_response(data)
+ return Response({"count": len(data), "results": data})
@llma_track_latency("llma_prompts_create")
@monitor(feature=None, endpoint="llma_prompts_create", method="POST")
diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.py
index c7d05a9bf8b8..a02159ca160f 100644
--- a/posthog/api/llm_prompt_serializers.py
+++ b/posthog/api/llm_prompt_serializers.py
@@ -194,6 +194,14 @@ class LLMPromptListQuerySerializer(serializers.Serializer):
"If omitted, the latest version of every prompt is returned."
),
)
+ resolve = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text=(
+ "Replace @@@prompt:...@@@ references with the referenced prompts' content in labeled "
+ "results with full content. Set to false to get the raw text with the reference tags."
+ ),
+ )
order_by = serializers.ChoiceField(
choices=list(ALLOWED_LIST_ORDERINGS),
required=False,
@@ -493,18 +501,41 @@ class LLMPromptLabelSummarySerializer(serializers.Serializer):
version = serializers.IntegerField(help_text="Prompt version this label currently points to.")
+class LLMPromptResolvedReferenceSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Name of the referenced prompt that was spliced in.")
+ version = serializers.IntegerField(help_text="Exact version whose content was spliced in.")
+ label = serializers.CharField( # type: ignore[assignment]
+ allow_null=True,
+ help_text="Label the reference used, or null when it pinned a version directly.",
+ )
+
+
class LLMPromptListSerializer(LLMPromptSerializer):
prompt_size_bytes = serializers.SerializerMethodField()
prompt_preview = serializers.SerializerMethodField()
all_labels = serializers.SerializerMethodField()
+ resolved_references = serializers.SerializerMethodField()
class Meta(LLMPromptSerializer.Meta):
- fields = [*LLMPromptSerializer.Meta.fields, "prompt_preview", "prompt_size_bytes", "all_labels"]
+ fields = [
+ *LLMPromptSerializer.Meta.fields,
+ "prompt_preview",
+ "prompt_size_bytes",
+ "all_labels",
+ "resolved_references",
+ ]
read_only_fields = fields
def get_prompt_size_bytes(self, instance: LLMPrompt) -> int:
return int(getattr(instance, "prompt_size_bytes", 0))
+ @extend_schema_field(LLMPromptResolvedReferenceSerializer(many=True, allow_null=True))
+ def get_resolved_references(self, instance: LLMPrompt) -> None:
+ # Serialization runs on raw rows; the viewset overwrites this after
+ # splicing references into labeled results. Null means resolution
+ # did not run for this row.
+ return None
+
@extend_schema_field(LLMPromptLabelSummarySerializer(many=True))
def get_all_labels(self, instance: LLMPrompt) -> list[dict[str, Any]]:
# A list row is one version (latest by default, the labeled one with ?label=),
@@ -559,15 +590,6 @@ class LLMPromptVersionSummarySerializer(serializers.ModelSerializer):
return sorted(label.name for label in instance.labels.all())
-class LLMPromptResolvedReferenceSerializer(serializers.Serializer):
- name = serializers.CharField(help_text="Name of the referenced prompt that was spliced in.")
- version = serializers.IntegerField(help_text="Exact version whose content was spliced in.")
- label = serializers.CharField( # type: ignore[assignment]
- allow_null=True,
- help_text="Label the reference used, or null when it pinned a version directly.",
- )
-
-
class LLMPromptPublicSerializer(serializers.Serializer):
id = serializers.UUIDField()
name = serializers.CharField()
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index 72803b5ffe65..d527c2acefd6 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -1488,7 +1488,12 @@ class TestLLMPromptLabelsAPI(APIBaseTest):
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
- expected_properties = {"prompt_fetch_path": "list", "prompt_label": "production", "prompt_count": 2}
+ expected_properties = {
+ "prompt_fetch_path": "list",
+ "prompt_label": "production",
+ "prompt_count": 2,
+ "prompt_resolved_reference_count": 0,
+ }
assert fetch_events() == [expected_properties]
mock_capture.assert_called_once()
assert mock_capture.call_args.kwargs["event_name"] == "$llm_prompt_fetched"
@@ -1506,7 +1511,9 @@ class TestLLMPromptLabelsAPI(APIBaseTest):
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}]
+ assert fetch_events() == [
+ {"prompt_fetch_path": "list", "prompt_label": None, "prompt_count": 2, "prompt_resolved_reference_count": 0}
+ ]
# A JWT is a background job impersonating a user, still an API caller.
impersonation_token = encode_jwt(
@@ -2285,3 +2292,62 @@ class TestLLMPromptDependenciesAPI(APIBaseTest):
)
response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/base/")
assert response.json()["referenced_by"] == []
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_labeled_list_resolves_references(self, _flag):
+ self._make_prompt("guardrails", prompt="G.", label="shared")
+ agent = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "Intro. @@@prompt:name=guardrails|label=shared@@@"},
+ format="json",
+ )
+ assert agent.status_code == status.HTTP_201_CREATED
+ self.client.put(
+ f"/api/environments/{self.team.id}/llm_prompts/name/agent/labels/production/",
+ data={"version": 1},
+ format="json",
+ )
+ self._make_prompt("plain", prompt="No tags.", label="production")
+ # Second row sharing the partial: provenance must survive the memo hit.
+ self._make_prompt("agent-two", prompt="Also @@@prompt:name=guardrails|label=shared@@@", label="production")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production&content=full")
+
+ assert response.status_code == status.HTTP_200_OK
+ rows = {row["name"]: row for row in response.json()["results"]}
+ assert rows["agent"]["prompt"] == "Intro. G."
+ assert rows["agent"]["resolved_references"] == [{"name": "guardrails", "version": 1, "label": "shared"}]
+ assert rows["agent-two"]["prompt"] == "Also G."
+ assert rows["agent-two"]["resolved_references"] == [{"name": "guardrails", "version": 1, "label": "shared"}]
+ assert rows["plain"]["prompt"] == "No tags."
+ assert rows["plain"]["resolved_references"] == []
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_labeled_list_fails_naming_the_prompt_whose_reference_cannot_resolve(self, _flag):
+ self._make_prompt("healthy", prompt="Fine.", label="production")
+ # Simulates a raced write: a labeled prompt referencing a prompt that no longer exists.
+ self._make_prompt("broken", prompt="@@@prompt:name=missing|version=1@@@", label="production")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production&content=full")
+
+ # Never a short page: a paginating client reads one as the end of the results.
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert response.json()["reference_name"] == "missing"
+ assert "broken" in response.json()["detail"]
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=False)
+ def test_labeled_list_passes_tags_through_when_flag_is_off(self, _flag):
+ self._make_prompt("guardrails", prompt="G.", label="shared")
+ self._make_prompt("agent", prompt="@@@prompt:name=guardrails|label=shared@@@", label="production")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/?label=production&content=full")
+
+ rows = {row["name"]: row for row in response.json()["results"]}
+ assert rows["agent"]["prompt"] == "@@@prompt:name=guardrails|label=shared@@@"
+ assert rows["agent"]["resolved_references"] is None
+
+ with patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True):
+ raw = self.client.get(
+ f"/api/environments/{self.team.id}/llm_prompts/?label=production&content=full&resolve=false"
+ )
+ assert raw.json()["results"][0]["prompt"] == "@@@prompt:name=guardrails|label=shared@@@"
diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.py
index 2fa0a8fdca31..ae40e6c2ca70 100644
--- a/products/ai_observability/backend/prompt_references.py
+++ b/products/ai_observability/backend/prompt_references.py
@@ -306,7 +306,11 @@ def _confirm_reference_missing(team_id: int, name: str, version: str | None, lab
return False
-def assemble_prompt_payload(team: Team, payload: dict[str, Any]) -> dict[str, Any]:
+def assemble_prompt_payload(
+ team: Team,
+ payload: dict[str, Any],
+ memoized: dict[tuple[str, str | None, str | None], tuple[str, int]] | None = None,
+) -> dict[str, Any]:
"""Splice referenced prompts' content into a fetched payload.
Each referenced prompt resolves through the same cached read path as the
@@ -325,8 +329,14 @@ def assemble_prompt_payload(team: Team, payload: dict[str, Any]) -> dict[str, An
# can hold ~35k copies of one small tag whose label later moves to a large
# version. Memoizing bounds the cache reads to the unique references, and
# the running size check aborts before a large assembly is materialized,
- # so a fetch never allocates more than the payload cap.
- memoized: dict[tuple[str, str | None, str | None], str] = {}
+ # so a fetch never allocates more than the payload cap. Callers assembling
+ # several payloads in one request pass a shared memo so a partial used by
+ # many prompts is read once.
+ if memoized is None:
+ memoized = {}
+ # Provenance is per payload while the memo may span payloads, so a memo
+ # hit must still record the reference for this payload's list.
+ seen: set[tuple[str, str | None, str | None]] = set()
# Running total of the true assembled size: each replacement removes the
# tag's bytes and adds the spliced content's bytes.
assembled_bytes = len(content.encode("utf-8"))
@@ -337,8 +347,8 @@ def assemble_prompt_payload(team: Team, payload: dict[str, Any]) -> dict[str, An
version = match.group("version")
label = match.group("label")
key = (name, version, label)
- child_content = memoized.get(key)
- if child_content is None:
+ cached = memoized.get(key)
+ if cached is None:
child = get_prompt_by_name_from_cache(
team, name, int(version) if version is not None else None, label=label
)
@@ -369,8 +379,12 @@ def assemble_prompt_payload(team: Team, payload: dict[str, Any]) -> dict[str, An
message=f"The referenced prompt '{name}' contains references of its own and cannot be spliced in.",
missing=False,
)
- memoized[key] = child_content
- resolved.append({"name": name, "version": child["version"], "label": label})
+ cached = (child_content, int(child["version"]))
+ memoized[key] = cached
+ child_content, child_version = cached
+ if key not in seen:
+ seen.add(key)
+ resolved.append({"name": name, "version": child_version, "label": label})
assembled_bytes += len(child_content.encode("utf-8")) - len(match.group(0).encode("utf-8"))
if assembled_bytes > MAX_PROMPT_PAYLOAD_BYTES:
raise PromptReferenceResolutionError(
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index d3564858c3c7..a3c87ba3d9e4 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -2739,6 +2739,18 @@ export interface LLMPromptLabelSummaryApi {
version: number
}
+export interface LLMPromptResolvedReferenceApi {
+ /** Name of the referenced prompt that was spliced in. */
+ name: string
+ /** Exact version whose content was spliced in. */
+ version: number
+ /**
+ * Label the reference used, or null when it pinned a version directly.
+ * @nullable
+ */
+ label: string | null
+}
+
/**
* Optional JSON object with model parameters or any agent configuration (e.g. model, temperature, tools). Versioned with the prompt and returned as-is when fetching it. Don't store secrets here: config is returned to anyone who can read the prompt.
* @nullable
@@ -2778,6 +2790,8 @@ export interface LLMPromptListApi {
readonly prompt_preview: string
readonly prompt_size_bytes: number
readonly all_labels: readonly LLMPromptLabelSummaryApi[]
+ /** @nullable */
+ readonly resolved_references: readonly LLMPromptResolvedReferenceApi[] | null
}
export interface PaginatedLLMPromptListListApi {
@@ -2837,18 +2851,6 @@ export interface LLMPromptApi {
*/
export type LLMPromptPublicApiConfig = { [key: string]: unknown } | null
-export interface LLMPromptResolvedReferenceApi {
- /** Name of the referenced prompt that was spliced in. */
- name: string
- /** Exact version whose content was spliced in. */
- version: number
- /**
- * Label the reference used, or null when it pinned a version directly.
- * @nullable
- */
- label: string | null
-}
-
export interface LLMPromptPublicApi {
id: string
name: string
@@ -3765,6 +3767,10 @@ export type LlmPromptsListParams = {
* @minLength 1
*/
order_by?: string
+ /**
+ * Replace @@@prompt:...@@@ references with the referenced prompts' content in labeled results with full content. Set to false to get the raw text with the reference tags.
+ */
+ resolve?: boolean
/**
* Optional substring filter applied to prompt names and prompt content.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 90bf89368e67..963d80323fd8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53714,6 +53714,18 @@ export namespace Schemas {
*/
export type LLMPromptListConfig = { [key: string]: unknown } | null;
+ export interface LLMPromptResolvedReference {
+ /** Name of the referenced prompt that was spliced in. */
+ name: string;
+ /** Exact version whose content was spliced in. */
+ version: number;
+ /**
+ * Label the reference used, or null when it pinned a version directly.
+ * @nullable
+ */
+ label: string | null;
+ }
+
export interface LLMPromptList {
readonly id: string;
/** Unique prompt name using letters, numbers, hyphens, and underscores only. */
@@ -53747,6 +53759,8 @@ export namespace Schemas {
readonly prompt_preview: string;
readonly prompt_size_bytes: number;
readonly all_labels: readonly LLMPromptLabelSummary[];
+ /** @nullable */
+ readonly resolved_references: readonly LLMPromptResolvedReference[] | null;
}
/**
@@ -53755,18 +53769,6 @@ export namespace Schemas {
*/
export type LLMPromptPublicConfig = { [key: string]: unknown } | null;
- export interface LLMPromptResolvedReference {
- /** Name of the referenced prompt that was spliced in. */
- name: string;
- /** Exact version whose content was spliced in. */
- version: number;
- /**
- * Label the reference used, or null when it pinned a version directly.
- * @nullable
- */
- label: string | null;
- }
-
export interface LLMPromptPublic {
id: string;
name: string;
@@ -110430,6 +110432,10 @@ export namespace Schemas {
* @minLength 1
*/
order_by?: string;
+ /**
+ * Replace @@@prompt:...@@@ references with the referenced prompts' content in labeled results with full content. Set to false to get the raw text with the reference tags.
+ */
+ resolve?: boolean;
/**
* Optional substring filter applied to prompt names and prompt content.
*/
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index b9908e33273d..617ffabadeff 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -2090,6 +2090,8 @@ export const llmPromptsListQueryLabelMax = 128
export const llmPromptsListQueryOrderByDefault = `-created_at`
+export const llmPromptsListQueryResolveDefault = true
+
export const LlmPromptsListQueryParams = () => zod.object({
content: zod
.enum(['full', 'preview', 'none'])
@@ -2115,6 +2117,12 @@ export const LlmPromptsListQueryParams = () => zod.object({
.describe(
"Field to sort the prompt list by. Prefix with '-' for descending order.\n\n\* `name` - name\n\* `-name` - -name\n\* `created_at` - created_at\n\* `-created_at` - -created_at\n\* `updated_at` - updated_at\n\* `-updated_at` - -updated_at\n\* `version` - version\n\* `-version` - -version\n\* `latest_version` - latest_version\n\* `-latest_version` - -latest_version\n\* `version_count` - version_count\n\* `-version_count` - -version_count\n\* `first_version_created_at` - first_version_created_at\n\* `-first_version_created_at` - -first_version_created_at\n\* `prompt_size_bytes` - prompt_size_bytes\n\* `-prompt_size_bytes` - -prompt_size_bytes"
),
+ resolve: zod
+ .boolean()
+ .default(llmPromptsListQueryResolveDefault)
+ .describe(
+ "Replace @@@prompt:...@@@ references with the referenced prompts' content in labeled results with full content. Set to false to get the raw text with the reference tags."
+ ),
search: zod.string().optional().describe('Optional substring filter applied to prompt names and prompt content.'),
})