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): resolve partial references in internal prompt reads (#107590)

Juraj Majerik867f0978a6b3
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 2086294fae9a..a2098647fdfd 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -8,7 +8,6 @@ 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
from rest_framework.decorators import action
@@ -68,7 +67,7 @@ from posthog.auth import (
)
from posthog.event_usage import report_team_action, report_user_action
from posthog.exceptions_capture import capture_exception
-from posthog.models import Team, User
+from posthog.models import User
from posthog.permissions import AccessControlPermission
from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottle
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
@@ -82,6 +81,7 @@ from products.ai_observability.backend.prompt_references import (
PromptReferenceResolutionError,
assemble_prompt_payload,
get_active_references_to,
+ prompt_partials_enabled,
)
logger = structlog.get_logger(__name__)
@@ -90,27 +90,6 @@ PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"
PROMPT_FETCHED_EVENT_SOURCE = "llm_prompt_management"
-PROMPT_PARTIALS_FLAG = "prompt-partials"
-
-
-def prompt_partials_enabled(team: Team) -> bool:
- """Kill switch for fetch-time reference resolution. Flag off = tags pass through as plain text."""
- try:
- return bool(
- posthoganalytics.feature_enabled(
- PROMPT_PARTIALS_FLAG,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- group_properties={"organization": {"id": str(team.organization_id)}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- # Flag service unavailable must not take down the SDK fetch path.
- return False
-
-
@extend_schema(extensions={"x-product": "llm_analytics"})
class LLMPromptViewSet(
TeamAndOrgViewSetMixin,
diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.py
index a6a276f4e6c3..8fe43b779f54 100644
--- a/products/ai_observability/backend/prompt_references.py
+++ b/products/ai_observability/backend/prompt_references.py
@@ -5,6 +5,8 @@ from typing import Any
from django.db import InterfaceError, OperationalError
from django.db.models import Q
+import structlog
+import posthoganalytics
from rest_framework import serializers
from posthog.dataclasses import frozen
@@ -14,6 +16,8 @@ from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
+logger = structlog.get_logger(__name__)
+
# 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
@@ -435,3 +439,47 @@ def assemble_prompt_payload(
assembled = PROMPT_REFERENCE_REGEX.sub(_splice, content)
return {**payload, "prompt": assembled, "resolved_references": resolved}
+
+
+PROMPT_PARTIALS_FLAG = "prompt-partials"
+
+
+def prompt_partials_enabled(team: Team) -> bool:
+ """Kill switch for reference resolution. Flag off = tags pass through as plain text."""
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ PROMPT_PARTIALS_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ # Flag service unavailable must not take down a prompt fetch.
+ return False
+
+
+def resolve_prompt_references(team: Team, content: str) -> str | None:
+ """Splice referenced partials into a managed prompt's `content`.
+
+ Internal features that read a team's managed prompt by name must resolve
+ reference tags the same way the SDK fetch path does, so a raw tag never
+ reaches an LLM. Returns `content` unchanged when the feature is off or there
+ is nothing to resolve, the assembled text when every reference resolves, or
+ None when a reference cannot be resolved so the caller falls back to its
+ in-code default prompt instead of sending a raw tag.
+ """
+ if not content or not PROMPT_REFERENCE_REGEX.search(content):
+ return content
+ if not prompt_partials_enabled(team):
+ return content
+ try:
+ return assemble_prompt_payload(team, {"name": "", "prompt": content})["prompt"]
+ except Exception:
+ # A broken reference or a cache outage must not send a raw tag to the model, but
+ # the caller only sees None, so record why here to separate it from an absent prompt.
+ logger.warning("prompt_reference_resolution_failed", team_id=team.id, exc_info=True)
+ return None
diff --git a/products/ai_observability/backend/test/test_prompt_references.py b/products/ai_observability/backend/test/test_prompt_references.py
index 493aced51500..23a88e8a3c80 100644
--- a/products/ai_observability/backend/test/test_prompt_references.py
+++ b/products/ai_observability/backend/test/test_prompt_references.py
@@ -1,9 +1,14 @@
+from unittest.mock import MagicMock, patch
+
from django.test import SimpleTestCase
from parameterized import parameterized
+from products.ai_observability.backend import prompt_references
from products.ai_observability.backend.prompt_references import PromptReference, parse_prompt_references
+RESOLVER = "products.ai_observability.backend.prompt_references"
+
class TestParsePromptReferences(SimpleTestCase):
@parameterized.expand(
@@ -57,3 +62,38 @@ class TestParsePromptReferences(SimpleTestCase):
)
def test_parse(self, _name: str, text: str, expected: list[PromptReference]) -> None:
assert parse_prompt_references(text) == expected
+
+
+class TestResolvePromptReferences(SimpleTestCase):
+ def setUp(self) -> None:
+ self.team = MagicMock()
+
+ def test_returns_content_unchanged_when_no_references(self) -> None:
+ with patch(f"{RESOLVER}.get_prompt_by_name_from_cache") as cache:
+ result = prompt_references.resolve_prompt_references(self.team, "plain prompt, no tags")
+ assert result == "plain prompt, no tags"
+ cache.assert_not_called()
+
+ @patch(f"{RESOLVER}.prompt_partials_enabled", return_value=False)
+ def test_passes_through_raw_tags_when_flag_off(self, _flag: MagicMock) -> None:
+ content = "before @@@prompt:name=foo|label=live@@@ after"
+ with patch(f"{RESOLVER}.get_prompt_by_name_from_cache") as cache:
+ result = prompt_references.resolve_prompt_references(self.team, content)
+ assert result == content
+ cache.assert_not_called()
+
+ @patch(f"{RESOLVER}.prompt_partials_enabled", return_value=True)
+ @patch(f"{RESOLVER}.get_prompt_by_name_from_cache")
+ def test_splices_referenced_content_when_flag_on(self, cache: MagicMock, _flag: MagicMock) -> None:
+ cache.return_value = {"prompt": "CHILD", "version": 2}
+ result = prompt_references.resolve_prompt_references(self.team, "before @@@prompt:name=foo|label=live@@@ after")
+ assert result == "before CHILD after"
+
+ @patch(f"{RESOLVER}.prompt_partials_enabled", return_value=True)
+ @patch(f"{RESOLVER}.get_prompt_by_name_from_cache")
+ def test_returns_none_when_reference_unresolvable(self, cache: MagicMock, _flag: MagicMock) -> None:
+ # A referenced prompt that holds a tag of its own can't be spliced in; the caller
+ # must fall back to its default rather than send a raw tag to the model.
+ cache.return_value = {"prompt": "nested @@@prompt:name=bar|label=live@@@", "version": 1}
+ result = prompt_references.resolve_prompt_references(self.team, "before @@@prompt:name=foo|label=live@@@ after")
+ assert result is None
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
index 6f4438a36baa..06e137bf87b5 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py
@@ -7,6 +7,8 @@ from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
+from products.ai_observability.backend.prompt_references import resolve_prompt_references
+
from ee.hogai.chat_agent.sql.prompts import CORE_MEMORY_USAGE_INSTRUCTION, HOGQL_QUERY_WRITING_RULES
logger = structlog.get_logger(__name__)
@@ -94,8 +96,10 @@ def resolve_prompt(team: Team, name: str, default: str) -> str:
if cached is not None:
stored = cached.get("prompt")
if isinstance(stored, str) and stored.strip():
- _capture_prompt_source(team, name, "managed")
- return stored
+ resolved = resolve_prompt_references(team, stored)
+ if resolved is not None:
+ _capture_prompt_source(team, name, "managed")
+ return resolved
_capture_prompt_source(team, name, "fallback")
return default
diff --git a/products/exports/backend/temporal/subscriptions/llm_change_summary.py b/products/exports/backend/temporal/subscriptions/llm_change_summary.py
index e165dbb25ffd..bc11bcb8716c 100644
--- a/products/exports/backend/temporal/subscriptions/llm_change_summary.py
+++ b/products/exports/backend/temporal/subscriptions/llm_change_summary.py
@@ -132,11 +132,15 @@ def _get_managed_prompt(team: Team | None, prompt_name: str, fallback: str) -> s
try:
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
+ from products.ai_observability.backend.prompt_references import resolve_prompt_references
+
result = get_prompt_by_name_from_cache(team, prompt_name)
if result and "prompt" in result:
- logger.info("prompt_source", prompt_name=prompt_name, source="managed", team_id=team.id)
- SUBSCRIPTION_PROMPT_SOURCE.labels(prompt_name=prompt_name, source="managed").inc()
- return normalize_prompt_to_string(result["prompt"])
+ resolved = resolve_prompt_references(team, normalize_prompt_to_string(result["prompt"]))
+ if resolved is not None:
+ logger.info("prompt_source", prompt_name=prompt_name, source="managed", team_id=team.id)
+ SUBSCRIPTION_PROMPT_SOURCE.labels(prompt_name=prompt_name, source="managed").inc()
+ return resolved
except Exception as e:
capture_exception(e)
logger.warning("managed_prompt_fetch_failed", prompt_name=prompt_name, error=str(e))
diff --git a/products/pulse/backend/generation/prompts.py b/products/pulse/backend/generation/prompts.py
index 02bd03fdfad8..7baa265be6ae 100644
--- a/products/pulse/backend/generation/prompts.py
+++ b/products/pulse/backend/generation/prompts.py
@@ -9,6 +9,8 @@ from posthog.exceptions_capture import capture_exception
from posthog.llm_prompt import normalize_prompt_to_string
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
+from products.ai_observability.backend.prompt_references import resolve_prompt_references
+
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -32,8 +34,10 @@ def _get_managed_prompt(team: Team | None, prompt_name: str, fallback: str) -> s
try:
result = get_prompt_by_name_from_cache(team, prompt_name)
if result and "prompt" in result:
- PULSE_PROMPT_SOURCE.labels(prompt_name=prompt_name, source="managed").inc()
- return normalize_prompt_to_string(result["prompt"])
+ resolved = resolve_prompt_references(team, normalize_prompt_to_string(result["prompt"]))
+ if resolved is not None:
+ PULSE_PROMPT_SOURCE.labels(prompt_name=prompt_name, source="managed").inc()
+ return resolved
except Exception as exc:
capture_exception(exc)
logger.warning("pulse_managed_prompt_fetch_failed", prompt_name=prompt_name, error=str(exc))
diff --git a/products/user_interviews/backend/logic.py b/products/user_interviews/backend/logic.py
index 1ead70330124..663827112d5b 100644
--- a/products/user_interviews/backend/logic.py
+++ b/products/user_interviews/backend/logic.py
@@ -12,10 +12,15 @@ from collections.abc import Mapping
from typing import Any
from uuid import UUID, uuid4
+import structlog
+
from posthog.dataclasses import frozen
from posthog.ingress.dispatch.database import bounded_statement_timeout
from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.models.team import Team
+from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
+from products.ai_observability.backend.prompt_references import resolve_prompt_references
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
from products.user_interviews.backend.models import (
EmailWithDisplayNameValidator,
@@ -23,6 +28,8 @@ from products.user_interviews.backend.models import (
UserInterviewClassification,
)
+logger = structlog.get_logger(__name__)
+
# distinct_id rules ported from rust/capture (`CAPTURE_V1_DISTINCT_ID_MAX_SIZE` and
# `ILLEGAL_DISTINCT_IDS` in v1/analytics/constants.rs). On the shared interview link these are
# best-effort person/session linkage hints from an untrusted public page, so an invalid value is
@@ -257,3 +264,24 @@ def has_replied(*, team_id: int, topic_id: UUID, interviewee_identifier: str) ->
.exclude(classifications__contains=[UserInterviewClassification.ABANDONED])
.exists()
)
+
+
+def resolve_first_message_template(team: Team, prompt_name: str, default: str) -> str:
+ """Return the team's managed first-message prompt, or `default`.
+
+ Splices in any referenced partials so a raw reference tag never reaches the
+ voice agent. Falls back to `default` on a lookup failure, an absent or empty
+ managed prompt, or an unresolvable reference.
+ """
+ try:
+ cached = get_prompt_by_name_from_cache(team, prompt_name)
+ except Exception as err:
+ logger.warning("user_interviews_first_message_prompt_lookup_failed", team_id=team.id, error=str(err))
+ return default
+ if cached is not None:
+ template = cached.get("prompt")
+ if isinstance(template, str) and template.strip():
+ resolved = resolve_prompt_references(team, template)
+ if resolved is not None:
+ return resolved
+ return default
diff --git a/products/user_interviews/backend/presentation/webhooks.py b/products/user_interviews/backend/presentation/webhooks.py
index c4c12248a269..379e033e739d 100644
--- a/products/user_interviews/backend/presentation/webhooks.py
+++ b/products/user_interviews/backend/presentation/webhooks.py
@@ -32,13 +32,13 @@ from posthog.ingress.views import build_webhook_view
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.rate_limit import IPThrottle
-from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
from ..facade.api import is_shared_interviewee_context, valid_distinct_id, valid_session_id
from ..logic import (
RESPONDENT_KEY_MAX_CHARS,
RESPONDENT_NAME_MAX_CHARS,
clean_field,
+ resolve_first_message_template,
resolve_share,
shared_interviewee_identifier,
)
@@ -159,20 +159,7 @@ def _normalise_topic(topic_text: str) -> str:
def _resolve_first_message_template(team: Team) -> str:
- try:
- cached = get_prompt_by_name_from_cache(team, FIRST_MESSAGE_PROMPT_NAME)
- except Exception as err:
- logger.warning(
- "user_interviews_first_message_prompt_lookup_failed",
- team_id=team.id,
- error=str(err),
- )
- return DEFAULT_FIRST_MESSAGE_TEMPLATE
- if cached is not None:
- template = cached.get("prompt")
- if isinstance(template, str) and template.strip():
- return template
- return DEFAULT_FIRST_MESSAGE_TEMPLATE
+ return resolve_first_message_template(team, FIRST_MESSAGE_PROMPT_NAME, DEFAULT_FIRST_MESSAGE_TEMPLATE)
def _build_first_message(