: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(prompts): show which prompts reference this one and warn on label moves (#103037)
Juraj Majerikdd182fda01a2
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex 74c1d1ca843b..37ff2e90cf76 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -76,7 +76,11 @@ from products.access_control.backend.presentation.access_control import AccessCofrom products.ai_observability.backend.activity_logging import log_llm_prompt_activityfrom products.ai_observability.backend.api.metrics import llma_track_latencyfrom products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outline-from products.ai_observability.backend.prompt_references import PromptReferenceResolutionError, assemble_prompt_payload+from products.ai_observability.backend.prompt_references import (+ PromptReferenceResolutionError,+ assemble_prompt_payload,+ get_active_references_to,+)PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"PROMPT_FETCHED_EVENT_SOURCE = "llm_prompt_management"@@ -517,6 +521,7 @@ class LLMPromptViewSet("versions": self._serialize_version_summaries(versions),"has_more": has_more,"labels": LLMPromptLabelSerializer(get_prompt_labels(self.team, prompt_name), many=True).data,+ "referenced_by": get_active_references_to(self.team.id, prompt_name),})diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.pyindex 2f83f69c026e..c7d05a9bf8b8 100644--- a/posthog/api/llm_prompt_serializers.py+++ b/posthog/api/llm_prompt_serializers.py@@ -658,6 +658,18 @@ class LLMPromptLabelSerializer(serializers.ModelSerializer):return instance.prompt.version+class LLMPromptReferencedBySerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Prompt whose latest or labeled version references this prompt.")+ label = serializers.CharField( # type: ignore[assignment]+ allow_null=True,+ help_text="Label of this prompt the reference follows, or null when it pins a version.",+ )+ version = serializers.IntegerField(+ allow_null=True,+ help_text="Version of this prompt the reference pins, or null when it follows a label.",+ )++class LLMPromptResolveResponseSerializer(serializers.Serializer):prompt = LLMPromptSerializer()versions = LLMPromptVersionSummarySerializer(many=True)@@ -666,3 +678,11 @@ class LLMPromptResolveResponseSerializer(serializers.Serializer):many=True,help_text="All labels on this prompt with the version each one currently points to, across all versions (not just the returned page).",)+ referenced_by = LLMPromptReferencedBySerializer(+ many=True,+ help_text=(+ "Prompts whose latest or labeled version references this prompt, with the label or version "+ "each reference uses. Empty when nothing references this prompt. At most 100 entries, "+ "ordered by prompt name."+ ),+ )diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 0333ce7d9631..10c3bd7227f8 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -2192,3 +2192,23 @@ class TestLLMPromptDependenciesAPI(APIBaseTest):assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLEassert response.json()["reference_name"] == "guardrails"++ def test_resolve_reports_active_incoming_references(self):+ self._make_prompt("base", label="production")+ self.client.post(+ f"/api/environments/{self.team.id}/llm_prompts/",+ data={"name": "parent", "prompt": "@@@prompt:name=base|label=production@@@"},+ format="json",+ )++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/base/")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["referenced_by"] == [{"name": "parent", "label": "production", "version": None}]++ self.client.patch(+ f"/api/environments/{self.team.id}/llm_prompts/name/parent/",+ data={"prompt": "no more references", "base_version": 1},+ format="json",+ )+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/base/")+ assert response.json()["referenced_by"] == []diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.pyindex cd721126a2fa..2fa0a8fdca31 100644--- a/products/ai_observability/backend/prompt_references.py+++ b/products/ai_observability/backend/prompt_references.py@@ -31,6 +31,10 @@ PROMPT_REFERENCE_REGEX = re.compile()MAX_PROMPT_REFERENCES = 20+# Incoming references are unbounded (any number of prompts can reference one+# partial), so surfaces listing them cap the result. Existence checks stay+# correct: over the cap still means "referenced".+MAX_ACTIVE_REFERENCE_RESULTS = 100@frozen@@ -75,13 +79,25 @@ def get_active_referencing_parent_names(team_id: int, child_name: str) -> list[srecorded before validation existed must not let a prompt block its ownarchival."""- return sorted(+ return sorted({reference["name"] for reference in get_active_references_to(team_id, child_name)})+++def get_active_references_to(team_id: int, child_name: str) -> list[dict[str, Any]]:+ """Active incoming references with the selector each parent used.++ `label` set means the parent follows that label of this prompt, so moving+ it propagates; `version` set means the parent pinned that version and+ nothing propagates to it.+ """+ rows = (LLMPromptDependency.objects.filter(team_id=team_id, child_name=child_name, prompt__deleted=False).filter(Q(prompt__is_latest=True) | Q(prompt__labels__isnull=False)).exclude(parent_name=child_name)- .values_list("parent_name", flat=True)+ .values_list("parent_name", "child_label", "child_version").distinct()+ .order_by("parent_name", "child_label", "child_version")[:MAX_ACTIVE_REFERENCE_RESULTS])+ return [{"name": name, "label": label, "version": version} for name, label, version in rows]def get_active_parents_referencing_label(team_id: int, prompt_name: str, label_name: str) -> list[str]:diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex e5ca9ddea6ee..ca36ebd4e839 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -2941,12 +2941,29 @@ export interface LLMPromptVersionSummaryApi {readonly labels: readonly string[]}+export interface LLMPromptReferencedByApi {+ /** Prompt whose latest or labeled version references this prompt. */+ name: string+ /**+ * Label of this prompt the reference follows, or null when it pins a version.+ * @nullable+ */+ label: string | null+ /**+ * Version of this prompt the reference pins, or null when it follows a label.+ * @nullable+ */+ version: number | null+}+export interface LLMPromptResolveResponseApi {prompt: LLMPromptApiversions: LLMPromptVersionSummaryApi[]has_more: boolean/** All labels on this prompt with the version each one currently points to, across all versions (not just the returned page). */labels: LLMPromptLabelApi[]+ /** Prompts whose latest or labeled version references this prompt, with the label or version each reference uses. Empty when nothing references this prompt. At most 100 entries, ordered by prompt name. */+ referenced_by: LLMPromptReferencedByApi[]}/**diff --git a/products/ai_observability/frontend/prompts/llmPromptLogic.ts b/products/ai_observability/frontend/prompts/llmPromptLogic.tsindex 221fc2dc23f4..2162a956ce38 100644--- a/products/ai_observability/frontend/prompts/llmPromptLogic.ts+++ b/products/ai_observability/frontend/prompts/llmPromptLogic.ts@@ -44,7 +44,12 @@ import {llmPromptsNameRetrieve,llmPromptsResolveNameRetrieve,} from '../generated/api'-import type { LLMPromptLabelApi, LLMPromptPublicApi, LLMPromptResolveResponseApi } from '../generated/api.schemas'+import type {+ LLMPromptLabelApi,+ LLMPromptPublicApi,+ LLMPromptReferencedByApi,+ LLMPromptResolveResponseApi,+} from '../generated/api.schemas'import { llmPromptsLogic } from './llmPromptsLogic'import { LLM_PROMPTS_FORCE_RELOAD_PARAM } from './llmPromptsLogic'import { LLMPrompt, LLMPromptVersionSummary } from './types'@@ -123,6 +128,7 @@ export interface ResolvedLLMPrompt extends LLMPrompt {versions: LLMPromptVersionSummary[]has_more: booleanlabels: LLMPromptLabelApi[]+ referenced_by: LLMPromptReferencedByApi[]}export function isPrompt(prompt: LLMPrompt | ResolvedLLMPrompt | PromptFormValues | null): prompt is ResolvedLLMPrompt {@@ -180,6 +186,7 @@ function getResolvedPrompt(response: LLMPromptResolveResponseApi): ResolvedLLMPrversions: response.versions as unknown as LLMPromptVersionSummary[],has_more: response.has_more,labels: response.labels ?? [],+ referenced_by: response.referenced_by ?? [],}}@@ -256,6 +263,7 @@ export interface llmPromptLogicValues {promptUsageTrendQuery: InsightVizNodepromptVariables: string[]publishConflict: PublishConflict | null+ referencedBy: LLMPromptReferencedByApi[]relatedTracesQuery: DataTableNode | nullrelatedTracesQueryOverride: DataTableNode | nullresolvedPreview: LLMPromptPublicApi | null@@ -472,6 +480,7 @@ export interface llmPromptLogicMeta {isEditMode: (mode: PromptMode, arg: any) => booleanversions: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => LLMPromptVersionSummary[]canLoadMoreVersions: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => boolean+ referencedBy: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => LLMPromptReferencedByApi[]promptLabels: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => LLMPromptLabelApi[]labelsByVersion: (promptLabels: LLMPromptLabelApi[]) => Record<number, LLMPromptLabelApi[]>isDiffVisible: (compareVersion: number | null) => boolean@@ -803,6 +812,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([versions: optimisticVersions,has_more: currentPrompt.has_more,labels: currentPrompt.labels,+ referenced_by: currentPrompt.referenced_by,})actions.setPromptFormValues(getPromptFormDefaults(savedPrompt))actions.setMode(PromptMode.View)@@ -821,6 +831,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([versions: [],has_more: false,labels: [],+ referenced_by: [],})actions.setPromptFormValues(getPromptFormDefaults(savedPrompt))}@@ -971,6 +982,11 @@ export const llmPromptLogic = kea<llmPromptLogicType>([(prompt: PromptFormValues | ResolvedLLMPrompt | null) => (isPrompt(prompt) ? prompt.has_more : false),],+ referencedBy: [+ (s) => [s.prompt],+ (prompt: PromptFormValues | ResolvedLLMPrompt | null): LLMPromptReferencedByApi[] =>+ prompt && isPrompt(prompt) ? (prompt.referenced_by ?? []) : [],+ ],promptLabels: [(s) => [s.prompt],(prompt: PromptFormValues | ResolvedLLMPrompt | null): LLMPromptLabelApi[] =>@@ -1266,6 +1282,9 @@ export const llmPromptLogic = kea<llmPromptLogicType>([labelName,fromVersion: existing.version,toVersion: version,+ followedBy: values.referencedBy+ .filter((reference) => reference.label === labelName)+ .map((reference) => reference.name),onMove: () => asyncActions.setLabel(labelName, version),})return@@ -1479,7 +1498,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([if (existingPrompt) {return {- prompt: { ...existingPrompt, versions: [], has_more: false, labels: [] },+ prompt: { ...existingPrompt, versions: [], has_more: false, labels: [], referenced_by: [] },promptForm: getPromptFormDefaults(existingPrompt),versionsLoading: false,}diff --git a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx b/products/ai_observability/frontend/prompts/promptSceneComponents.tsxindex 8aaf1e59c924..d1553042250c 100644--- a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx+++ b/products/ai_observability/frontend/prompts/promptSceneComponents.tsx@@ -86,6 +86,7 @@ export function PromptViewDetails(): JSX.Element {isShowingResolvedPreview,resolvedPreview,resolvedPreviewLoading,+ referencedBy,} = useValues(llmPromptLogic)const { toggleMarkdownRendering, setCompareVersion, toggleResolvedPreview } = useActions(llmPromptLogic)const markdownContainerRef = useRef<HTMLDivElement>(null)@@ -188,6 +189,19 @@ export function PromptViewDetails(): JSX.Element {{!isShowingResolvedPreview && <PromptReferenceTags text={promptText} />}+ {referencedBy.length > 0 && (+ <div className="flex flex-wrap items-center gap-1" data-attr="llma-prompt-used-by">+ <span className="text-xs text-secondary">Used by:</span>+ {[...new Set(referencedBy.map((reference) => reference.name))].map((name) => (+ <Link key={name} to={urls.aiObservabilityPrompt(name)}>+ <LemonTag type="completion" size="small">+ {name}+ </LemonTag>+ </Link>+ ))}+ </div>+ )}+{variables.length > 0 && (<div className="flex flex-wrap items-center gap-1"><span className="text-xs text-secondary">Variables:</span>diff --git a/products/ai_observability/frontend/prompts/utils.tsx b/products/ai_observability/frontend/prompts/utils.tsxindex 328bc0a47384..c1e343d65594 100644--- a/products/ai_observability/frontend/prompts/utils.tsx+++ b/products/ai_observability/frontend/prompts/utils.tsx@@ -94,16 +94,22 @@ export function openMoveLabelDialog({labelName,fromVersion,toVersion,+ followedBy = [],onMove,}: {labelName: stringfromVersion: numbertoVersion: number+ followedBy?: string[]onMove: () => Promise<void>}): void {+ const propagationNote =+ followedBy.length > 0+ ? ` This also updates the content of ${followedBy.join(', ')}, which reference${followedBy.length === 1 ? 's' : ''} this prompt through this label.`+ : ''LemonDialog.open({title: 'Move label?',- description: `${labelName}: v${fromVersion} → v${toVersion}. Anything fetching this prompt by this label picks up the change within seconds.`,+ description: `${labelName}: v${fromVersion} → v${toVersion}. Anything fetching this prompt by this label picks up the change within seconds.${propagationNote}`,shouldAwaitSubmit: true,primaryButton: {children: 'Move',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5ebcab34d584..28684bf57ce8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -51409,6 +51409,21 @@ export namespace Schemas {first_version_created_at: string;}+ export interface LLMPromptReferencedBy {+ /** Prompt whose latest or labeled version references this prompt. */+ name: string;+ /**+ * Label of this prompt the reference follows, or null when it pins a version.+ * @nullable+ */+ label: string | null;+ /**+ * Version of this prompt the reference pins, or null when it follows a label.+ * @nullable+ */+ version: number | null;+ }+export interface LLMPromptReferencedConflict {/** What is still referenced and what to do next. */detail: string;@@ -51434,6 +51449,8 @@ export namespace Schemas {has_more: boolean;/** All labels on this prompt with the version each one currently points to, across all versions (not just the returned page). */labels: LLMPromptLabel[];+ /** Prompts whose latest or labeled version references this prompt, with the label or version each reference uses. Empty when nothing references this prompt. At most 100 entries, ordered by prompt name. */+ referenced_by: LLMPromptReferencedBy[];}export interface LLMPromptSetLabel {