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(prompts): track references between prompts (#101224)

Juraj Majerikcda0cc613f85
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 67b78fbe70c2..225cef85427c 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -259,6 +259,7 @@ rules:
|LoopTrigger
|LLMModelConfiguration
|LLMPrompt
+ |LLMPromptDependency
|LLMPromptLabel
|LLMProviderKey
|LLMSkill
@@ -667,6 +668,7 @@ rules:
|NotebookWidgetInstance
|LLMModelConfiguration
|LLMPrompt
+ |LLMPromptDependency
|LLMPromptLabel
|LLMProviderKey
|LLMSkill
diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.py
index a3e2935e9bc3..356e39e16707 100644
--- a/posthog/api/llm_prompt_serializers.py
+++ b/posthog/api/llm_prompt_serializers.py
@@ -2,6 +2,8 @@ import re
import json
from typing import Any
+from django.db import transaction
+
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
@@ -10,6 +12,7 @@ from posthog.llm_prompt import normalize_prompt_to_string
from products.ai_observability.backend.activity_logging import prompt_activity_item_id
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outline
+from products.ai_observability.backend.prompt_references import record_prompt_references
class LLMPromptOutlineEntrySerializer(serializers.Serializer):
@@ -453,12 +456,15 @@ class LLMPromptSerializer(serializers.ModelSerializer):
request = self.context["request"]
team = self.context["get_team"]()
- return LLMPrompt.objects.create(
- team=team,
- created_by=request.user,
- is_latest=True,
- **validated_data,
- )
+ with transaction.atomic():
+ prompt = LLMPrompt.objects.create(
+ team=team,
+ created_by=request.user,
+ is_latest=True,
+ **validated_data,
+ )
+ record_prompt_references(prompt)
+ return prompt
class LLMPromptLabelSummarySerializer(serializers.Serializer):
diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.py
index 7ca8fd193239..eb9a8806577a 100644
--- a/posthog/api/services/llm_prompt.py
+++ b/posthog/api/services/llm_prompt.py
@@ -18,6 +18,7 @@ from products.ai_observability.backend.models.llm_prompt import (
LLMPromptLabel,
annotate_llm_prompt_version_history_metadata,
)
+from products.ai_observability.backend.prompt_references import record_prompt_references
SYNC_ARCHIVE_VERSION_INVALIDATION_LIMIT = 100
MAX_PROMPT_VERSION = 2000
@@ -225,6 +226,7 @@ def publish_prompt_version(
created_by=user,
version_description=version_description,
)
+ record_prompt_references(published_prompt)
changes = [
Change(
@@ -305,6 +307,7 @@ def duplicate_prompt(
if "unique_llm_prompt_latest_per_team" in str(err) or "unique_llm_prompt_version_per_team" in str(err):
raise LLMPromptDuplicateNameConflictError() from err
raise
+ record_prompt_references(new_prompt)
# One entry per prompt history: the copy records where it came from, the
# source records where it went.
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index c3f7ad03a371..f43776fdb961 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -24,7 +24,8 @@ from posthog.api.services.llm_prompt import MAX_PROMPT_VERSION
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottle
-from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel
+from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
+from products.ai_observability.backend.prompt_references import MAX_PROMPT_REFERENCES
class TestLLMPromptAPI(APIBaseTest):
@@ -1685,3 +1686,102 @@ class TestLLMPromptLabelNameValidationNoDB(SimpleTestCase):
)
def test_accepts_valid_label_name(self, _label: str, good_name: str) -> None:
assert validate_prompt_label_name_value(good_name) == good_name
+
+
+class TestLLMPromptDependenciesAPI(APIBaseTest):
+ def _dependency_rows(self, parent_name: str) -> list[tuple[str, int | None, str | None, int]]:
+ return sorted(
+ LLMPromptDependency.objects.filter(team=self.team, parent_name=parent_name).values_list(
+ "child_name", "child_version", "child_label", "prompt__version"
+ )
+ )
+
+ def test_create_records_references(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={
+ "name": "agent",
+ "prompt": (
+ "@@@prompt:name=guardrails|label=production@@@\n"
+ "@@@prompt:name=tone|version=3@@@\n"
+ "@@@prompt:name=guardrails|label=production@@@\n"
+ "@@@prompt:name=not-a-ref@@@"
+ ),
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert self._dependency_rows("agent") == [
+ ("guardrails", None, "production", 1),
+ ("tone", 3, None, 1),
+ ]
+
+ def test_create_without_references_writes_no_rows(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "plain", "prompt": "No tags, only {{variables}}."},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert self._dependency_rows("plain") == []
+
+ def test_publish_records_references_for_the_new_version_only(self):
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|version=1@@@"},
+ format="json",
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/llm_prompts/name/agent/",
+ data={"prompt": "@@@prompt:name=tone|label=prod@@@", "base_version": 1},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert self._dependency_rows("agent") == [
+ ("guardrails", 1, None, 1),
+ ("tone", None, "prod", 2),
+ ]
+
+ def test_duplicate_records_references_for_the_copy(self):
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "original", "prompt": "@@@prompt:name=guardrails|label=production@@@"},
+ format="json",
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/name/original/duplicate/",
+ data={"new_name": "copy"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert self._dependency_rows("copy") == [("guardrails", None, "production", 1)]
+
+ def test_create_rejects_more_than_the_reference_limit(self):
+ def tags(count: int) -> str:
+ return "\n".join(f"@@@prompt:name=partial-{i}|version=1@@@" for i in range(count))
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "over-limit", "prompt": tags(MAX_PROMPT_REFERENCES + 1)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "too_many_references"
+ assert LLMPrompt.objects.filter(team=self.team, name="over-limit").count() == 0
+ assert self._dependency_rows("over-limit") == []
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "at-limit", "prompt": tags(MAX_PROMPT_REFERENCES)},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert len(self._dependency_rows("at-limit")) == MAX_PROMPT_REFERENCES
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index fdbaf92571cd..32014c464eeb 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -103,6 +103,7 @@ IntervieweeContext
KernelRuntime
LLMModelConfiguration
LLMPrompt
+LLMPromptDependency
LLMPromptLabel
LLMProviderKey
LLMSkill
diff --git a/products/ai_observability/backend/migrations/0049_llmpromptdependency.py b/products/ai_observability/backend/migrations/0049_llmpromptdependency.py
new file mode 100644
index 000000000000..43063fdd0d62
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0049_llmpromptdependency.py
@@ -0,0 +1,76 @@
+# Generated by Django 5.2.17 on 2026-09-15 19:53
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0048_evaluationbackfill"),
+ ("posthog", "1355_datadeletionrequest_ddr_team_created_at_idx"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="LLMPromptDependency",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("parent_name", models.CharField(max_length=255)),
+ ("child_name", models.CharField(max_length=255)),
+ ("child_version", models.PositiveIntegerField(blank=True, null=True)),
+ (
+ "child_label",
+ models.CharField(blank=True, max_length=128, null=True),
+ ),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ (
+ "prompt",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="references",
+ to="ai_observability.llmprompt",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_llmpromptdependency",
+ "indexes": [models.Index(fields=["team", "child_name"], name="llm_prompt_dep_team_child")],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("child_label__isnull", True),
+ ("child_version__isnull", False),
+ ),
+ models.Q(
+ ("child_label__isnull", False),
+ ("child_version__isnull", True),
+ ),
+ _connector="OR",
+ ),
+ name="llm_prompt_dependency_version_xor_label",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 81173f149890..ad7a807018e4 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0048_evaluationbackfill
+0049_llmpromptdependency
diff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.py
index 743c35f83e1d..e1245e8a2037 100644
--- a/products/ai_observability/backend/models/__init__.py
+++ b/products/ai_observability/backend/models/__init__.py
@@ -7,7 +7,7 @@ from .evaluation_directories import EvaluationDirectory
from .evaluation_reports import EvaluationReport, EvaluationReportRun
from .evaluations import Evaluation
from .instrumentation_checklist import AIObservabilityChecklistItemState
-from .llm_prompt import LLMPrompt, LLMPromptLabel
+from .llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
from .llm_traces_summaries import LLMTraceSummary
from .model_configuration import LLMModelConfiguration
from .parser_recipe import ParserRecipe
@@ -33,6 +33,7 @@ __all__ = [
"DatasetRevision",
"LLMModelConfiguration",
"LLMPrompt",
+ "LLMPromptDependency",
"LLMPromptLabel",
"ParserRecipe",
"LLMProvider",
diff --git a/products/ai_observability/backend/models/llm_prompt.py b/products/ai_observability/backend/models/llm_prompt.py
index 5d4942af6066..36914aefd01e 100644
--- a/products/ai_observability/backend/models/llm_prompt.py
+++ b/products/ai_observability/backend/models/llm_prompt.py
@@ -106,6 +106,50 @@ class LLMPromptLabel(ModelActivityMixin, UUIDModel):
updated_at = models.DateTimeField(auto_now=True)
+class LLMPromptDependency(UUIDModel):
+ """One `@@@prompt:...@@@` reference found in a prompt version's content.
+
+ Rows are written when a version is created and are immutable like the
+ version row they belong to. The fetch path does not read this table; it
+ re-parses the content. The table exists for validation (reference and
+ nesting checks at publish), archive protection, and "used by" lookups,
+ all of which need the reverse direction: who references prompt X?
+
+ Like LLMPromptLabel, `child_name` keys the referenced prompt family by
+ name rather than FK, because prompts have no parent entity and the
+ referenced family's version rows keep changing.
+
+ Also like LLMPromptLabel, deliberately not on TeamScopedRootMixin: rows
+ must stay in the same team-space as the LLMPrompt rows they point into
+ (see the LLMPromptLabel docstring). Migrate all three models together.
+ """
+
+ class Meta:
+ constraints = [
+ models.CheckConstraint(
+ check=models.Q(child_version__isnull=False, child_label__isnull=True)
+ | models.Q(child_version__isnull=True, child_label__isnull=False),
+ name="llm_prompt_dependency_version_xor_label",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["team", "child_name"], name="llm_prompt_dep_team_child"),
+ ]
+ db_table = "posthog_llmpromptdependency"
+
+ prompt = models.ForeignKey(LLMPrompt, on_delete=models.CASCADE, related_name="references")
+ parent_name = models.CharField(max_length=255)
+ child_name = models.CharField(max_length=255)
+ child_version = models.PositiveIntegerField(null=True, blank=True)
+ child_label = models.CharField(max_length=128, null=True, blank=True)
+
+ # db_constraint=False for the same reason as LLMPromptLabel: a real FK to the
+ # hot posthog_team table locks the parent during migration.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+
+ created_at = models.DateTimeField(default=timezone.now)
+
+
def annotate_llm_prompt_version_history_metadata(queryset: QuerySet[LLMPrompt]) -> QuerySet[LLMPrompt]:
active_versions = LLMPrompt.objects.filter(team_id=OuterRef("team_id"), name=OuterRef("name"), deleted=False)
diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.py
new file mode 100644
index 000000000000..3de000a5ab9e
--- /dev/null
+++ b/products/ai_observability/backend/prompt_references.py
@@ -0,0 +1,92 @@
+import re
+
+from rest_framework import serializers
+
+from posthog.dataclasses import frozen
+from posthog.llm_prompt import normalize_prompt_to_string
+
+from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency
+
+# Both charsets are enforced at write time (validate_prompt_name_value,
+# validate_prompt_label_name_value in posthog/api/llm_prompt_serializers.py),
+# so a tag can always be parsed without escaping. Widening either charset
+# requires revisiting this grammar.
+# The length bounds mirror the LLMPromptDependency columns (name varchar(255),
+# label varchar(128)) and the int4 range for version, so an oversized value
+# makes the tag plain text instead of failing the row insert and rolling back
+# the write that carried it. Versions start at 1 and have no leading zeros,
+# so a selector that can never match a version is plain text too.
+PROMPT_REFERENCE_REGEX = re.compile(
+ r"@@@prompt:"
+ r"name=(?P<name>[A-Za-z0-9_-]{1,255})\|"
+ r"(?:version=(?P<version>[1-9][0-9]{0,8})|label=(?P<label>[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?))"
+ r"@@@"
+)
+
+MAX_PROMPT_REFERENCES = 20
+
+
+@frozen
+class PromptReference:
+ """One `@@@prompt:...@@@` tag inside a prompt's text.
+
+ Exactly one of `version` and `label` is set: a version reference is pinned
+ forever, a label reference follows wherever the label points.
+ """
+
+ name: str
+ version: int | None
+ label: str | None
+
+ def __post_init__(self) -> None:
+ if (self.version is None) == (self.label is None):
+ raise ValueError("A prompt reference has exactly one of version and label.")
+
+
+def parse_prompt_references(text: str) -> list[PromptReference]:
+ """Extract references in order of appearance, duplicates included."""
+ references = []
+ for match in PROMPT_REFERENCE_REGEX.finditer(text):
+ version = match.group("version")
+ references.append(
+ PromptReference(
+ name=match.group("name"),
+ version=int(version) if version is not None else None,
+ label=match.group("label"),
+ )
+ )
+ return references
+
+
+def record_prompt_references(prompt: LLMPrompt) -> list[LLMPromptDependency]:
+ """Persist the references found in a version's content.
+
+ Call once per version row, inside the transaction that creates it, so the
+ dependency rows share the version row's immutability and atomicity.
+ """
+ references = parse_prompt_references(normalize_prompt_to_string(prompt.prompt))
+ if not references:
+ return []
+ # A tag repeated in the content is one dependency edge.
+ unique_references = list(dict.fromkeys(references))
+ # Raised from here so create, publish, and duplicate all share the one
+ # check; the surrounding transaction rolls the version row back with it.
+ if len(unique_references) > MAX_PROMPT_REFERENCES:
+ raise serializers.ValidationError(
+ f"A prompt can reference at most {MAX_PROMPT_REFERENCES} other prompts. "
+ "Remove some references and try again.",
+ code="too_many_references",
+ )
+ return LLMPromptDependency.objects.bulk_create(
+ [
+ LLMPromptDependency(
+ team_id=prompt.team_id,
+ prompt=prompt,
+ parent_name=prompt.name,
+ child_name=reference.name,
+ child_version=reference.version,
+ child_label=reference.label,
+ )
+ for reference in unique_references
+ ]
+ )
diff --git a/products/ai_observability/backend/test/test_prompt_references.py b/products/ai_observability/backend/test/test_prompt_references.py
new file mode 100644
index 000000000000..493aced51500
--- /dev/null
+++ b/products/ai_observability/backend/test/test_prompt_references.py
@@ -0,0 +1,59 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.ai_observability.backend.prompt_references import PromptReference, parse_prompt_references
+
+
+class TestParsePromptReferences(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "version_pin",
+ "Intro @@@prompt:name=guardrails|version=3@@@ outro",
+ [PromptReference(name="guardrails", version=3, label=None)],
+ ),
+ (
+ "label_follow",
+ "@@@prompt:name=guardrails|label=production@@@",
+ [PromptReference(name="guardrails", version=None, label="production")],
+ ),
+ (
+ "multiple_in_order_with_duplicates",
+ "@@@prompt:name=a|version=1@@@ x @@@prompt:name=b|label=prod@@@ y @@@prompt:name=a|version=1@@@",
+ [
+ PromptReference(name="a", version=1, label=None),
+ PromptReference(name="b", version=None, label="prod"),
+ PromptReference(name="a", version=1, label=None),
+ ],
+ ),
+ ("no_tags", "Just {{variables}} and plain text", []),
+ ("bare_name_not_a_reference", "@@@prompt:name=guardrails@@@", []),
+ ("missing_value_not_a_reference", "@@@prompt:name=guardrails|version=@@@", []),
+ ("uppercase_label_not_a_reference", "@@@prompt:name=guardrails|label=Production@@@", []),
+ ("name_with_invalid_chars_not_a_reference", "@@@prompt:name=guard.rails|version=1@@@", []),
+ ("unterminated_not_a_reference", "@@@prompt:name=guardrails|version=1", []),
+ (
+ "name_at_column_limit",
+ f"@@@prompt:name={'a' * 255}|version=1@@@",
+ [PromptReference(name="a" * 255, version=1, label=None)],
+ ),
+ ("name_over_column_limit_not_a_reference", f"@@@prompt:name={'a' * 256}|version=1@@@", []),
+ (
+ "label_at_column_limit",
+ f"@@@prompt:name=guardrails|label={'b' * 128}@@@",
+ [PromptReference(name="guardrails", version=None, label="b" * 128)],
+ ),
+ ("label_over_column_limit_not_a_reference", f"@@@prompt:name=guardrails|label={'b' * 129}@@@", []),
+ (
+ "version_at_digit_limit",
+ "@@@prompt:name=guardrails|version=999999999@@@",
+ [PromptReference(name="guardrails", version=999_999_999, label=None)],
+ ),
+ ("version_over_digit_limit_not_a_reference", "@@@prompt:name=guardrails|version=9999999999@@@", []),
+ ("version_zero_not_a_reference", "@@@prompt:name=guardrails|version=0@@@", []),
+ ("version_with_leading_zero_not_a_reference", "@@@prompt:name=guardrails|version=03@@@", []),
+ ]
+ )
+ def test_parse(self, _name: str, text: str, expected: list[PromptReference]) -> None:
+ assert parse_prompt_references(text) == expected