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): Add prompt version labels (#70862)

Juraj Majerik1ff16e06330b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 387808a5afa4..4aaff1e080a0 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -188,6 +188,7 @@ rules:
|LogsView
|LLMModelConfiguration
|LLMPrompt
+ |LLMPromptLabel
|LLMProviderKey
|LLMSkill
|LLMTraceSummary
@@ -486,6 +487,7 @@ rules:
|LiveDebuggerBreakpoint
|LLMModelConfiguration
|LLMPrompt
+ |LLMPromptLabel
|LLMProviderKey
|LLMSkill
|LLMTraceSummary
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index d74d7cca6f63..6e793464ba97 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -18,6 +18,7 @@ from posthog.api.llm_prompt_serializers import (
LLMPromptDuplicateSerializer,
LLMPromptFetchQuerySerializer,
LLMPromptGetByNameQuerySerializer,
+ LLMPromptLabelSerializer,
LLMPromptListQuerySerializer,
LLMPromptListSerializer,
LLMPromptPublicSerializer,
@@ -25,13 +26,18 @@ from posthog.api.llm_prompt_serializers import (
LLMPromptResolveQuerySerializer,
LLMPromptResolveResponseSerializer,
LLMPromptSerializer,
+ LLMPromptSetLabelSerializer,
LLMPromptVersionSummarySerializer,
+ validate_prompt_label_name_value,
)
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.llm_prompt import (
LLMPromptDuplicateNameConflictError,
LLMPromptEditError,
+ LLMPromptLabelConflictError,
+ LLMPromptLabelLimitError,
+ LLMPromptLabelNotFoundError,
LLMPromptNotFoundError,
LLMPromptVersionConflictError,
LLMPromptVersionLimitError,
@@ -41,7 +47,9 @@ from posthog.api.services.llm_prompt import (
get_latest_prompts_queryset,
get_prompt_by_name_from_db,
publish_prompt_version,
+ remove_prompt_label,
resolve_versions_page,
+ set_prompt_label,
)
from posthog.auth import (
JwtAuthentication,
@@ -455,6 +463,98 @@ class LLMPromptViewSet(
)
return Response(self._serialize_prompt(new_prompt), status=status.HTTP_201_CREATED)
+ @extend_schema(request=LLMPromptSetLabelSerializer, responses={200: LLMPromptLabelSerializer})
+ @action(
+ methods=["PUT"],
+ detail=False,
+ url_path=r"name/(?P<prompt_name>[^/]+)/labels/(?P<label_name>[^/]+)",
+ required_scopes=["llm_prompt:write"],
+ )
+ @llma_track_latency("llma_prompts_set_label")
+ @monitor(feature=None, endpoint="llma_prompts_set_label", method="PUT")
+ def set_label(self, request: Request, prompt_name: str = "", label_name: str = "", **kwargs) -> Response:
+ auth_error = self._ensure_web_authenticated(request)
+ if auth_error is not None:
+ return auth_error
+
+ label_name = validate_prompt_label_name_value(label_name)
+ payload = LLMPromptSetLabelSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+ version = payload.validated_data["version"]
+
+ try:
+ result = set_prompt_label(
+ self.team,
+ user=cast(User, request.user),
+ prompt_name=prompt_name,
+ label_name=label_name,
+ version=version,
+ )
+ except LLMPromptNotFoundError:
+ return Response(
+ {"detail": f"Prompt '{prompt_name}' has no version {version}."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ except LLMPromptLabelConflictError:
+ return Response(
+ {"detail": "This label was changed by someone else at the same time. Try again."},
+ status=status.HTTP_409_CONFLICT,
+ )
+ except LLMPromptLabelLimitError as err:
+ return Response(
+ {
+ "detail": (
+ f"This prompt has reached the maximum of {err.max_labels} labels. "
+ "Remove a label to add a new one."
+ ),
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ report_user_action(
+ cast(User, request.user),
+ "llma prompt label set",
+ {
+ "prompt_name": prompt_name,
+ "label": label_name,
+ "version": version,
+ "previous_version": result.previous_version,
+ "created": result.created,
+ },
+ team=self.team,
+ request=request,
+ )
+ return Response(
+ LLMPromptLabelSerializer(result.label).data,
+ status=status.HTTP_201_CREATED if result.created else status.HTTP_200_OK,
+ )
+
+ @extend_schema(responses={204: None})
+ @set_label.mapping.delete
+ @llma_track_latency("llma_prompts_delete_label")
+ @monitor(feature=None, endpoint="llma_prompts_delete_label", method="DELETE")
+ def delete_label(self, request: Request, prompt_name: str = "", label_name: str = "", **kwargs) -> Response:
+ auth_error = self._ensure_web_authenticated(request)
+ if auth_error is not None:
+ return auth_error
+
+ try:
+ remove_prompt_label(self.team, prompt_name=prompt_name, label_name=label_name)
+ except LLMPromptLabelNotFoundError:
+ return Response(
+ {"detail": f"Label '{label_name}' not found on prompt '{prompt_name}'."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+
+ report_user_action(
+ cast(User, request.user),
+ "llma prompt label deleted",
+ {"prompt_name": prompt_name, "label": label_name},
+ team=self.team,
+ request=request,
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
@extend_schema(parameters=[LLMPromptListQuerySerializer])
@llma_track_latency("llma_prompts_list")
@monitor(feature=None, endpoint="llma_prompts_list", method="GET")
diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.py
index ac1890e51439..5a15d4c8522e 100644
--- a/posthog/api/llm_prompt_serializers.py
+++ b/posthog/api/llm_prompt_serializers.py
@@ -9,6 +9,7 @@ from posthog.api.shared import UserBasicSerializer
from products.ai_observability.backend.models.llm_prompt import (
LLMPrompt,
+ LLMPromptLabel,
get_prompt_outline,
normalize_prompt_to_string,
)
@@ -48,6 +49,39 @@ def validate_prompt_payload_size(prompt_payload: Any) -> Any:
return prompt_payload
+RESERVED_PROMPT_LABEL_NAMES = {"latest"}
+PROMPT_LABEL_NAME_MAX_LENGTH = 128
+# Allowlist keeps label names unambiguous everywhere they travel: URL path segments,
+# cache keys, and the label= argument in customer code.
+PROMPT_LABEL_NAME_REGEX = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$")
+
+
+def validate_prompt_label_name_value(value: str) -> str:
+ value = value.strip()
+ if not value or len(value) > PROMPT_LABEL_NAME_MAX_LENGTH:
+ raise serializers.ValidationError(
+ f"Label names must be between 1 and {PROMPT_LABEL_NAME_MAX_LENGTH} characters.",
+ code="invalid_label_name",
+ )
+ if value.lower() in RESERVED_PROMPT_LABEL_NAMES:
+ raise serializers.ValidationError(
+ "'latest' is a reserved label. It always points to the newest version.",
+ code="reserved_label_name",
+ )
+ if value.isdigit():
+ raise serializers.ValidationError(
+ "Label names cannot be numbers only, to avoid confusion with version numbers.",
+ code="invalid_label_name",
+ )
+ if not PROMPT_LABEL_NAME_REGEX.match(value):
+ raise serializers.ValidationError(
+ "Use lowercase letters, numbers, dots (.), hyphens (-) and underscores (_), "
+ "starting and ending with a letter or number.",
+ code="invalid_label_name",
+ )
+ return value
+
+
CONTENT_MODE_CHOICES = ["full", "preview", "none"]
CONTENT_MODE_HELP = (
"Controls how much prompt content is included in the response. "
@@ -184,6 +218,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):
version_count = serializers.SerializerMethodField()
first_version_created_at = serializers.SerializerMethodField()
outline = serializers.SerializerMethodField()
+ labels = serializers.SerializerMethodField()
class Meta:
model = LLMPrompt
@@ -202,6 +237,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):
"version_count",
"first_version_created_at",
"outline",
+ "labels",
]
read_only_fields = [
"id",
@@ -215,6 +251,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):
"version_count",
"first_version_created_at",
"outline",
+ "labels",
]
extra_kwargs = {
"name": {"help_text": "Unique prompt name using letters, numbers, hyphens, and underscores only."},
@@ -228,6 +265,15 @@ class LLMPromptSerializer(serializers.ModelSerializer):
def get_outline(self, instance: LLMPrompt) -> list[dict[str, Any]]:
return get_prompt_outline(instance.prompt)
+ @extend_schema_field(
+ serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Names of the labels currently pointing at this version.",
+ )
+ )
+ def get_labels(self, instance: LLMPrompt) -> list[str]:
+ return sorted(label.name for label in instance.labels.all())
+
def get_is_latest(self, instance: LLMPrompt) -> bool:
return bool(getattr(instance, "is_latest", False))
@@ -328,6 +374,7 @@ class LLMPromptListSerializer(LLMPromptSerializer):
class LLMPromptVersionSummarySerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
+ labels = serializers.SerializerMethodField()
class Meta:
model = LLMPrompt
@@ -338,9 +385,19 @@ class LLMPromptVersionSummarySerializer(serializers.ModelSerializer):
"created_by",
"created_at",
"is_latest",
+ "labels",
]
read_only_fields = fields
+ @extend_schema_field(
+ serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Names of the labels currently pointing at this version.",
+ )
+ )
+ def get_labels(self, instance: LLMPrompt) -> list[str]:
+ return sorted(label.name for label in instance.labels.all())
+
class LLMPromptPublicSerializer(serializers.Serializer):
id = serializers.UUIDField()
@@ -381,3 +438,38 @@ class LLMPromptResolveResponseSerializer(serializers.Serializer):
prompt = LLMPromptSerializer()
versions = LLMPromptVersionSummarySerializer(many=True)
has_more = serializers.BooleanField()
+
+
+class LLMPromptSetLabelSerializer(serializers.Serializer):
+ version = serializers.IntegerField(
+ min_value=1,
+ help_text=(
+ "Prompt version this label should point to. "
+ "If the label already exists on another version of the prompt, it is moved there."
+ ),
+ )
+
+
+class LLMPromptLabelSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+ version = serializers.SerializerMethodField()
+
+ class Meta:
+ model = LLMPromptLabel
+ fields = [
+ "id",
+ "name",
+ "prompt_name",
+ "version",
+ "created_by",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "name": {"help_text": "Label name, e.g. 'production'. Points to exactly one version of the prompt."},
+ "prompt_name": {"help_text": "Name of the prompt this label belongs to."},
+ }
+
+ def get_version(self, instance: LLMPromptLabel) -> int:
+ return instance.prompt.version
diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.py
index f0ee4554ee74..bc8d6ceabd34 100644
--- a/posthog/api/services/llm_prompt.py
+++ b/posthog/api/services/llm_prompt.py
@@ -11,16 +11,34 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
from posthog.storage.llm_prompt_cache import invalidate_prompt_latest_cache, invalidate_prompt_version_caches
-from products.ai_observability.backend.models.llm_prompt import LLMPrompt, annotate_llm_prompt_version_history_metadata
+from products.ai_observability.backend.models.llm_prompt import (
+ LLMPrompt,
+ LLMPromptLabel,
+ annotate_llm_prompt_version_history_metadata,
+)
SYNC_ARCHIVE_VERSION_INVALIDATION_LIMIT = 100
MAX_PROMPT_VERSION = 2000
+MAX_PROMPT_LABELS = 50
class LLMPromptNotFoundError(Exception):
pass
+class LLMPromptLabelNotFoundError(Exception):
+ pass
+
+
+class LLMPromptLabelConflictError(Exception):
+ pass
+
+
+@dataclass
+class LLMPromptLabelLimitError(Exception):
+ max_labels: int
+
+
@dataclass
class LLMPromptVersionConflictError(Exception):
current_version: int
@@ -85,7 +103,7 @@ def apply_prompt_edits(prompt_content: Any, edits: list[dict[str, str]]) -> Any:
def get_active_prompt_queryset(team: Team) -> QuerySet[LLMPrompt]:
return annotate_llm_prompt_version_history_metadata(
- LLMPrompt.objects.filter(team=team, deleted=False).select_related("created_by")
+ LLMPrompt.objects.filter(team=team, deleted=False).select_related("created_by").prefetch_related("labels")
)
@@ -124,6 +142,7 @@ def resolve_versions_page(
queryset = (
LLMPrompt.objects.filter(team=team, name=prompt_name, deleted=False)
.select_related("created_by")
+ .prefetch_related("labels")
.order_by("-version", "-created_at", "-id")
)
@@ -254,6 +273,8 @@ def archive_prompt(team: Team, prompt_name: str) -> list[int]:
is_latest=False,
)
+ LLMPromptLabel.objects.filter(team=team, prompt_name=prompt_name).delete()
+
def invalidate_caches_on_commit() -> None:
invalidate_prompt_latest_cache(team.id, prompt_name)
@@ -282,3 +303,72 @@ def archive_prompt(team: Team, prompt_name: str) -> list[int]:
transaction.on_commit(invalidate_caches_on_commit)
return prompt_versions
+
+
+@dataclass
+class PromptLabelSetResult:
+ label: LLMPromptLabel
+ previous_version: int | None
+ created: bool
+
+
+def set_prompt_label(
+ team: Team,
+ *,
+ user: User,
+ prompt_name: str,
+ label_name: str,
+ version: int,
+) -> PromptLabelSetResult:
+ """Point a label at a prompt version, creating or moving it.
+
+ "Set" is the only write verb: a label that already exists on another version is
+ moved, so the one-version-per-label invariant can't be violated through this path.
+ """
+ with transaction.atomic():
+ # Locked so a concurrent archive_prompt (which locks the same rows) can't mark the
+ # prompt deleted between this check and the label write, orphaning the label.
+ target = (
+ LLMPrompt.objects.select_for_update()
+ .filter(team=team, name=prompt_name, deleted=False, version=version)
+ .order_by("created_at", "id")
+ .first()
+ )
+ if target is None:
+ raise LLMPromptNotFoundError()
+
+ existing = (
+ LLMPromptLabel.objects.select_for_update()
+ .select_related("prompt")
+ .filter(team=team, prompt_name=prompt_name, name=label_name)
+ .first()
+ )
+ if existing is not None:
+ previous_version = existing.prompt.version
+ if existing.prompt_id != target.pk:
+ existing.prompt = target
+ existing.save()
+ return PromptLabelSetResult(label=existing, previous_version=previous_version, created=False)
+
+ if LLMPromptLabel.objects.filter(team=team, prompt_name=prompt_name).count() >= MAX_PROMPT_LABELS:
+ raise LLMPromptLabelLimitError(max_labels=MAX_PROMPT_LABELS)
+
+ try:
+ label = LLMPromptLabel.objects.create(
+ team=team,
+ prompt_name=prompt_name,
+ name=label_name,
+ prompt=target,
+ created_by=user,
+ )
+ except IntegrityError as err:
+ # Concurrent PUTs raced to create the same label; the other request won.
+ raise LLMPromptLabelConflictError() from err
+ return PromptLabelSetResult(label=label, previous_version=None, created=True)
+
+
+def remove_prompt_label(team: Team, *, prompt_name: str, label_name: str) -> None:
+ label = LLMPromptLabel.objects.filter(team=team, prompt_name=prompt_name, name=label_name).first()
+ if label is None:
+ raise LLMPromptLabelNotFoundError()
+ label.delete()
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index e7518e5683fb..308b9f9d92c5 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -7,14 +7,19 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.test import APIRequestFactory
from posthog.api.llm_prompt import LLMPromptViewSet
-from posthog.api.llm_prompt_serializers import MAX_PROMPT_PAYLOAD_BYTES, LLMPromptDuplicateSerializer
+from posthog.api.llm_prompt_serializers import (
+ MAX_PROMPT_PAYLOAD_BYTES,
+ LLMPromptDuplicateSerializer,
+ validate_prompt_label_name_value,
+)
from posthog.api.services.llm_prompt import MAX_PROMPT_VERSION
from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottle
-from products.ai_observability.backend.models.llm_prompt import LLMPrompt
+from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel
class TestLLMPromptAPI(APIBaseTest):
@@ -962,3 +967,170 @@ class TestLLMPromptDuplicateSerializerValidationNoDB(SimpleTestCase):
def test_accepts_valid_new_name(self) -> None:
serializer = LLMPromptDuplicateSerializer(data={"new_name": "a-valid_name1"})
assert serializer.is_valid(), serializer.errors
+
+
+class TestLLMPromptLabelsAPI(APIBaseTest):
+ def create_prompt_version(
+ self,
+ *,
+ name: str = "my-prompt",
+ prompt: Any = "Prompt content",
+ version: int = 1,
+ is_latest: bool = True,
+ ) -> LLMPrompt:
+ return LLMPrompt.objects.create(
+ team=self.team,
+ name=name,
+ prompt=prompt,
+ version=version,
+ is_latest=is_latest,
+ created_by=self.user,
+ )
+
+ def _label_url(self, prompt_name: str, label_name: str) -> str:
+ return f"/api/environments/{self.team.id}/llm_prompts/name/{prompt_name}/labels/{label_name}/"
+
+ def _set_label(self, prompt_name: str, label_name: str, version: int):
+ return self.client.put(self._label_url(prompt_name, label_name), data={"version": version}, format="json")
+
+ def _resolve_labels_by_version(self, prompt_name: str) -> dict[int, list[str]]:
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/{prompt_name}/")
+ assert response.status_code == status.HTTP_200_OK
+ return {entry["version"]: entry["labels"] for entry in response.json()["versions"]}
+
+ def test_set_label_creates_pointer_and_exposes_it_on_versions(self):
+ self.create_prompt_version(version=1, is_latest=False)
+ self.create_prompt_version(version=2)
+
+ response = self._set_label("my-prompt", "production", 1)
+
+ assert response.status_code == status.HTTP_201_CREATED
+ data = response.json()
+ assert data["name"] == "production"
+ assert data["prompt_name"] == "my-prompt"
+ assert data["version"] == 1
+ assert self._resolve_labels_by_version("my-prompt") == {1: ["production"], 2: []}
+
+ def test_set_label_moves_existing_label_instead_of_duplicating(self):
+ self.create_prompt_version(version=1, is_latest=False)
+ self.create_prompt_version(version=2)
+ assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED
+
+ response = self._set_label("my-prompt", "production", 2)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["version"] == 2
+ assert self._resolve_labels_by_version("my-prompt") == {1: [], 2: ["production"]}
+ assert LLMPromptLabel.objects.filter(team=self.team).count() == 1
+
+ def test_version_can_hold_multiple_labels(self):
+ self.create_prompt_version(version=1)
+ assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED
+ assert self._set_label("my-prompt", "staging", 1).status_code == status.HTTP_201_CREATED
+
+ assert self._resolve_labels_by_version("my-prompt") == {1: ["production", "staging"]}
+
+ def test_set_label_unknown_version_returns_404(self):
+ self.create_prompt_version(version=1)
+
+ response = self._set_label("my-prompt", "production", 7)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_set_label_rejects_invalid_name(self):
+ self.create_prompt_version(version=1)
+
+ response = self._set_label("my-prompt", "latest", 1)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_set_label_limit_blocks_creates_but_not_moves(self):
+ self.create_prompt_version(version=1, is_latest=False)
+ self.create_prompt_version(version=2)
+
+ with patch("posthog.api.services.llm_prompt.MAX_PROMPT_LABELS", 1):
+ assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED
+ assert self._set_label("my-prompt", "staging", 1).status_code == status.HTTP_400_BAD_REQUEST
+ assert self._set_label("my-prompt", "production", 2).status_code == status.HTTP_200_OK
+
+ def test_delete_label_removes_pointer(self):
+ self.create_prompt_version(version=1)
+ assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED
+
+ response = self.client.delete(self._label_url("my-prompt", "production"))
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert self._resolve_labels_by_version("my-prompt") == {1: []}
+
+ response = self.client.delete(self._label_url("my-prompt", "production"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ 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
+
+ response = self.client.post(f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/archive/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert LLMPromptLabel.objects.filter(team=self.team).count() == 0
+
+ def test_label_writes_forbidden_for_read_only_personal_api_key(self):
+ self.create_prompt_version(version=1)
+ api_key = self.create_personal_api_key_with_scopes(["llm_prompt:read"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ put_response = self._set_label("my-prompt", "production", 1)
+ delete_response = self.client.delete(self._label_url("my-prompt", "production"))
+
+ assert put_response.status_code == status.HTTP_403_FORBIDDEN
+ assert delete_response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_label_writes_allowed_for_write_scoped_personal_api_key(self):
+ self.create_prompt_version(version=1)
+ api_key = self.create_personal_api_key_with_scopes(["llm_prompt:write"])
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")
+
+ put_response = self._set_label("my-prompt", "production", 1)
+ # DELETE is a mapped method on the set_label action; it must share the
+ # action's required_scopes rather than fall back to "not supported" 403.
+ delete_response = self.client.delete(self._label_url("my-prompt", "production"))
+
+ assert put_response.status_code == status.HTTP_201_CREATED
+ assert delete_response.status_code == status.HTTP_204_NO_CONTENT
+
+
+class TestLLMPromptLabelNameValidationNoDB(SimpleTestCase):
+ # validate_prompt_label_name_value is a pure string check (no context, no DB). The endpoint's
+ # use of it is guarded by test_set_label_rejects_invalid_name.
+ @parameterized.expand(
+ [
+ ("uppercase", "Production"),
+ ("reserved_latest", "latest"),
+ ("reserved_latest_upper", "LATEST"),
+ ("numeric", "3"),
+ ("numeric_long", "42"),
+ ("space", "my label"),
+ ("slash", "prod/eu"),
+ ("leading_dash", "-prod"),
+ ("trailing_dot", "prod."),
+ ("empty", ""),
+ ("too_long", "a" * 129),
+ ("non_ascii", "café"),
+ ]
+ )
+ def test_rejects_invalid_label_name(self, _label: str, bad_name: str) -> None:
+ with self.assertRaises(DRFValidationError):
+ validate_prompt_label_name_value(bad_name)
+
+ @parameterized.expand(
+ [
+ ("word", "production"),
+ ("single_char", "a"),
+ ("digit_mix", "v2.rollout"),
+ ("dashes", "staging-eu"),
+ ("underscore", "tenant_b"),
+ ("max_length", "a" * 128),
+ ]
+ )
+ def test_accepts_valid_label_name(self, _label: str, good_name: str) -> None:
+ assert validate_prompt_label_name_value(good_name) == good_name
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index 7f426f8a5191..c4bcc388e16d 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -105,6 +105,7 @@ IntervieweeContext
KernelRuntime
LLMModelConfiguration
LLMPrompt
+LLMPromptLabel
LLMProviderKey
LLMSkill
LLMTraceSummary
diff --git a/products/ai_observability/backend/migrations/0023_llmpromptlabel.py b/products/ai_observability/backend/migrations/0023_llmpromptlabel.py
new file mode 100644
index 000000000000..d8a51ff7ee64
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0023_llmpromptlabel.py
@@ -0,0 +1,72 @@
+# Generated by Django 5.2.14 on 2026-07-14 19:15
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0022_add_generated_delivery_status"),
+ ("posthog", "1255_wizard_runs_rate_limit_and_provisioned_onboarding_reason"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="LLMPromptLabel",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=128)),
+ ("prompt_name", models.CharField(max_length=255)),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "prompt",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="labels",
+ to="ai_observability.llmprompt",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_llmpromptlabel",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "prompt_name", "name"),
+ name="unique_llm_prompt_label_per_prompt",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 51fddfd77b44..439eda06d283 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0022_add_generated_delivery_status
+0023_llmpromptlabel
diff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.py
index 281239b40423..c987ba6d0e35 100644
--- a/products/ai_observability/backend/models/__init__.py
+++ b/products/ai_observability/backend/models/__init__.py
@@ -4,7 +4,7 @@ from .datasets import Dataset, DatasetItem
from .evaluation_config import EvaluationConfig
from .evaluation_reports import EvaluationReport, EvaluationReportRun
from .evaluations import Evaluation
-from .llm_prompt import LLMPrompt
+from .llm_prompt import LLMPrompt, LLMPromptLabel
from .llm_traces_summaries import LLMTraceSummary
from .model_configuration import LLMModelConfiguration
from .parser_recipe import ParserRecipe
@@ -25,6 +25,7 @@ __all__ = [
"DatasetItem",
"LLMModelConfiguration",
"LLMPrompt",
+ "LLMPromptLabel",
"ParserRecipe",
"LLMProvider",
"LLMProviderKey",
diff --git a/products/ai_observability/backend/models/llm_prompt.py b/products/ai_observability/backend/models/llm_prompt.py
index 87c7dddfeaba..91615b381c7a 100644
--- a/products/ai_observability/backend/models/llm_prompt.py
+++ b/products/ai_observability/backend/models/llm_prompt.py
@@ -74,6 +74,49 @@ class LLMPrompt(UUIDModel):
deleted = models.BooleanField(default=False)
+class LLMPromptLabel(UUIDModel):
+ """A movable pointer from a name (e.g. "production") to exactly one version of a prompt.
+
+ Version rows are immutable; releasing a version means pointing a label at it and
+ rolling back means pointing it back. The (team, prompt_name, name) uniqueness is
+ what keeps fetch-by-label single-valued.
+
+ Deliberately not on TeamScopedRootMixin: LLMPrompt stores raw (possibly child-env)
+ team ids, and the mixin's canonical-team rewrite would put labels in a different
+ team-space than the prompt rows they point into. Migrate to fail-closed scoping
+ together with LLMPrompt.
+ """
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "prompt_name", "name"],
+ name="unique_llm_prompt_label_per_prompt",
+ ),
+ ]
+ db_table = "posthog_llmpromptlabel"
+
+ name = models.CharField(max_length=128)
+ # Prompts have no parent entity — version rows are grouped by name, so the label
+ # keys the prompt family by name and points at one version row via the FK below.
+ prompt_name = models.CharField(max_length=255)
+ prompt = models.ForeignKey(LLMPrompt, on_delete=models.CASCADE, related_name="labels")
+
+ # db_constraint=False: posthog_team / posthog_user are hot tables — adding a real FK
+ # constraint locks the parent table during migration.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ )
+
+ created_at = models.DateTimeField(default=timezone.now)
+ updated_at = models.DateTimeField(auto_now=True)
+
+
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/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 1dae95f0e5d6..7fa97a463074 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -2159,6 +2159,8 @@ export interface LLMPromptListApi {
readonly version_count: number
readonly first_version_created_at: string
readonly outline: readonly LLMPromptOutlineEntryApi[]
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[]
readonly prompt_preview: string
readonly prompt_size_bytes: number
}
@@ -2197,6 +2199,8 @@ export interface LLMPromptApi {
readonly version_count: number
readonly first_version_created_at: string
readonly outline: readonly LLMPromptOutlineEntryApi[]
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[]
}
export interface LLMPromptPublicApi {
@@ -2250,6 +2254,26 @@ export interface LLMPromptDuplicateApi {
new_name: string
}
+export interface LLMPromptSetLabelApi {
+ /**
+ * Prompt version this label should point to. If the label already exists on another version of the prompt, it is moved there.
+ * @minimum 1
+ */
+ version: number
+}
+
+export interface LLMPromptLabelApi {
+ readonly id: string
+ /** Label name, e.g. 'production'. Points to exactly one version of the prompt. */
+ readonly name: string
+ /** Name of the prompt this label belongs to. */
+ readonly prompt_name: string
+ readonly version: number
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ readonly updated_at: string
+}
+
export interface LLMPromptVersionSummaryApi {
readonly id: string
readonly version: number
@@ -2258,6 +2282,8 @@ export interface LLMPromptVersionSummaryApi {
readonly created_by: UserBasicApi
readonly created_at: string
readonly is_latest: boolean
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[]
}
export interface LLMPromptResolveResponseApi {
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index c40f7ab54417..9bbf4e96fcd0 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -32,8 +32,10 @@ import type {
LLMModelsListResponseApi,
LLMPromptApi,
LLMPromptDuplicateApi,
+ LLMPromptLabelApi,
LLMPromptPublicApi,
LLMPromptResolveResponseApi,
+ LLMPromptSetLabelApi,
LLMProviderKeyApi,
LlmAnalyticsClusteringJobsListParams,
LlmAnalyticsEvaluationReportsListParams,
@@ -1967,6 +1969,41 @@ export const llmPromptsNameDuplicateCreate = async (
})
}
+export const getLlmPromptsNameLabelsUpdateUrl = (projectId: string, promptName: string, labelName: string) => {
+ return `/api/projects/${projectId}/llm_prompts/name/${promptName}/labels/${labelName}/`
+}
+
+export const llmPromptsNameLabelsUpdate = async (
+ projectId: string,
+ promptName: string,
+ labelName: string,
+ lLMPromptSetLabelApi: LLMPromptSetLabelApi,
+ options?: RequestInit
+): Promise<LLMPromptLabelApi> => {
+ return apiMutator<LLMPromptLabelApi>(getLlmPromptsNameLabelsUpdateUrl(projectId, promptName, labelName), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(lLMPromptSetLabelApi),
+ })
+}
+
+export const getLlmPromptsNameLabelsDestroyUrl = (projectId: string, promptName: string, labelName: string) => {
+ return `/api/projects/${projectId}/llm_prompts/name/${promptName}/labels/${labelName}/`
+}
+
+export const llmPromptsNameLabelsDestroy = async (
+ projectId: string,
+ promptName: string,
+ labelName: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getLlmPromptsNameLabelsDestroyUrl(projectId, promptName, labelName), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getLlmPromptsResolveNameRetrieveUrl = (
projectId: string,
promptName: string,
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 6783a47e2ba5..7c801e994fe7 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -1830,6 +1830,15 @@ export const LlmPromptsNameDuplicateCreateBody = /* @__PURE__ */ zod.object({
),
})
+export const LlmPromptsNameLabelsUpdateBody = /* @__PURE__ */ zod.object({
+ version: zod
+ .number()
+ .min(1)
+ .describe(
+ 'Prompt version this label should point to. If the label already exists on another version of the prompt, it is moved there.'
+ ),
+})
+
export const taggersCreateBodyNameMax = 400
export const taggersCreateBodyTaggerTypeDefault = `llm`
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index 3fc2452a5443..c5209ea1a622 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -521,6 +521,35 @@ tools:
The response always includes `outline`, a flat list of markdown headings parsed from the prompt — useful
as a lightweight table of contents. Pass `content=none` to get the outline without the prompt payload,
or `content=preview` for a short `prompt_preview` snippet instead of the full prompt.
+ llma-prompt-label-delete:
+ operation: llm_prompts_name_labels_destroy
+ enabled: true
+ scopes:
+ - llm_prompt:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Delete prompt label
+ description: >
+ Remove a label from an LLM prompt. The label stops pointing at any version; recreate it with the set-label
+ tool if needed. Confirm nothing depends on the label before removing it.
+ llma-prompt-label-set:
+ operation: llm_prompts_name_labels_update
+ enabled: true
+ scopes:
+ - llm_prompt:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Set prompt label
+ description: >
+ Point a label (for example 'production') at a specific version of an LLM prompt. A label is a movable
+ pointer to exactly one version: if the label already exists on another version of this prompt, it is moved
+ there. Use labels to mark a version as released ('production', 'staging') or roll back by pointing the label
+ at an earlier version. Label names use lowercase letters, numbers, dots, hyphens and underscores; 'latest'
+ is reserved and numbers-only names are not allowed. Each prompt can have at most 50 labels.
llma-prompt-list:
operation: llm_prompts_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 90ae5459cb32..8fa4678c1c0b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5034,6 +5034,34 @@
"readOnlyHint": true
}
},
+ "llma-prompt-label-delete": {
+ "description": "Remove a label from an LLM prompt. The label stops pointing at any version; recreate it with the set-label tool if needed. Confirm nothing depends on the label before removing it.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Delete prompt label",
+ "title": "Delete prompt label",
+ "required_scopes": ["llm_prompt:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-prompt-label-set": {
+ "description": "Point a label (for example 'production') at a specific version of an LLM prompt. A label is a movable pointer to exactly one version: if the label already exists on another version of this prompt, it is moved there. Use labels to mark a version as released ('production', 'staging') or roll back by pointing the label at an earlier version. Label names use lowercase letters, numbers, dots, hyphens and underscores; 'latest' is reserved and numbers-only names are not allowed. Each prompt can have at most 50 labels.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Set prompt label",
+ "title": "Set prompt label",
+ "required_scopes": ["llm_prompt:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"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.",
"category": "AI observability",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 194ba13ab2dd..0dd98840c6ec 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5329,6 +5329,34 @@
"readOnlyHint": true
}
},
+ "llma-prompt-label-delete": {
+ "description": "Remove a label from an LLM prompt. The label stops pointing at any version; recreate it with the set-label tool if needed. Confirm nothing depends on the label before removing it.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Delete prompt label",
+ "title": "Delete prompt label",
+ "required_scopes": ["llm_prompt:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
+ "llma-prompt-label-set": {
+ "description": "Point a label (for example 'production') at a specific version of an LLM prompt. A label is a movable pointer to exactly one version: if the label already exists on another version of this prompt, it is moved there. Use labels to mark a version as released ('production', 'staging') or roll back by pointing the label at an earlier version. Label names use lowercase letters, numbers, dots, hyphens and underscores; 'latest' is reserved and numbers-only names are not allowed. Each prompt can have at most 50 labels.",
+ "category": "AI observability",
+ "feature": "llm_analytics",
+ "summary": "Set prompt label",
+ "title": "Set prompt label",
+ "required_scopes": ["llm_prompt:write"],
+ "annotations": {
+ "destructiveHint": true,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ }
+ },
"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.",
"category": "AI observability",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a05f03bc8bb4..894d8bb627ac 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32823,6 +32823,8 @@ export namespace Schemas {
readonly version_count: number;
readonly first_version_created_at: string;
readonly outline: readonly LLMPromptOutlineEntry[];
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[];
}
export interface LLMPromptDuplicate {
@@ -32840,6 +32842,18 @@ export namespace Schemas {
new: string;
}
+ export interface LLMPromptLabel {
+ readonly id: string;
+ /** Label name, e.g. 'production'. Points to exactly one version of the prompt. */
+ readonly name: string;
+ /** Name of the prompt this label belongs to. */
+ readonly prompt_name: string;
+ readonly version: number;
+ readonly created_by: UserBasic;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
export interface LLMPromptList {
readonly id: string;
/** Unique prompt name using letters, numbers, hyphens, and underscores only. */
@@ -32861,6 +32875,8 @@ export namespace Schemas {
readonly version_count: number;
readonly first_version_created_at: string;
readonly outline: readonly LLMPromptOutlineEntry[];
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[];
readonly prompt_preview: string;
readonly prompt_size_bytes: number;
}
@@ -32892,6 +32908,8 @@ export namespace Schemas {
readonly created_by: UserBasic;
readonly created_at: string;
readonly is_latest: boolean;
+ /** Names of the labels currently pointing at this version. */
+ readonly labels: readonly string[];
}
export interface LLMPromptResolveResponse {
@@ -32900,6 +32918,14 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface LLMPromptSetLabel {
+ /**
+ * Prompt version this label should point to. If the label already exists on another version of the prompt, it is moved there.
+ * @minimum 1
+ */
+ version: number;
+ }
+
/**
* Arbitrary key-value metadata.
*/
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 4a84f14ea9af..dab245368a91 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 56 enabled ops
+ * PostHog API - MCP 58 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1692,6 +1692,41 @@ export const LlmPromptsNameDuplicateCreateBody = /* @__PURE__ */ zod.object({
),
})
+export const llmPromptsNameLabelsUpdatePathLabelNameRegExp = new RegExp('^[^/]+$')
+export const llmPromptsNameLabelsUpdatePathPromptNameRegExp = new RegExp('^[^/]+$')
+
+export const LlmPromptsNameLabelsUpdateParams = /* @__PURE__ */ zod.object({
+ label_name: zod.string().regex(llmPromptsNameLabelsUpdatePathLabelNameRegExp),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ prompt_name: zod.string().regex(llmPromptsNameLabelsUpdatePathPromptNameRegExp),
+})
+
+export const LlmPromptsNameLabelsUpdateBody = /* @__PURE__ */ zod.object({
+ version: zod
+ .number()
+ .min(1)
+ .describe(
+ 'Prompt version this label should point to. If the label already exists on another version of the prompt, it is moved there.'
+ ),
+})
+
+export const llmPromptsNameLabelsDestroyPathLabelNameRegExp = new RegExp('^[^/]+$')
+export const llmPromptsNameLabelsDestroyPathPromptNameRegExp = new RegExp('^[^/]+$')
+
+export const LlmPromptsNameLabelsDestroyParams = /* @__PURE__ */ zod.object({
+ label_name: zod.string().regex(llmPromptsNameLabelsDestroyPathLabelNameRegExp),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ prompt_name: zod.string().regex(llmPromptsNameLabelsDestroyPathPromptNameRegExp),
+})
+
export const TaggersListParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index 1a73c32b725a..093a484b3d7e 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -61,6 +61,9 @@ import {
LlmPromptsCreateBody,
LlmPromptsNameDuplicateCreateBody,
LlmPromptsNameDuplicateCreateParams,
+ LlmPromptsNameLabelsDestroyParams,
+ LlmPromptsNameLabelsUpdateBody,
+ LlmPromptsNameLabelsUpdateParams,
LlmPromptsNamePartialUpdateBody,
LlmPromptsNamePartialUpdateParams,
LlmPromptsNameRetrieveParams,
@@ -802,6 +805,43 @@ const llmaPromptGet = (): ToolBase<typeof LlmaPromptGetSchema, Schemas.LLMPrompt
},
})
+const LlmaPromptLabelDeleteSchema = LlmPromptsNameLabelsDestroyParams.omit({ project_id: true })
+
+const llmaPromptLabelDelete = (): ToolBase<typeof LlmaPromptLabelDeleteSchema, unknown> => ({
+ name: 'llma-prompt-label-delete',
+ schema: LlmaPromptLabelDeleteSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaPromptLabelDeleteSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_prompts/name/${encodeURIComponent(String(params.prompt_name))}/labels/${encodeURIComponent(String(params.label_name))}/`,
+ })
+ return result
+ },
+})
+
+const LlmaPromptLabelSetSchema = LlmPromptsNameLabelsUpdateParams.omit({ project_id: true }).extend(
+ LlmPromptsNameLabelsUpdateBody.shape
+)
+
+const llmaPromptLabelSet = (): ToolBase<typeof LlmaPromptLabelSetSchema, Schemas.LLMPromptLabel> => ({
+ name: 'llma-prompt-label-set',
+ schema: LlmaPromptLabelSetSchema,
+ handler: async (context: Context, params: z.infer<typeof LlmaPromptLabelSetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.version !== undefined) {
+ body['version'] = params.version
+ }
+ const result = await context.api.request<Schemas.LLMPromptLabel>({
+ method: 'PUT',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_prompts/name/${encodeURIComponent(String(params.prompt_name))}/labels/${encodeURIComponent(String(params.label_name))}/`,
+ body,
+ })
+ return result
+ },
+})
+
const LlmaPromptListSchema = PromptListInputSchema
const llmaPromptList = (): ToolBase<
@@ -1569,6 +1609,8 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'llma-prompt-create': llmaPromptCreate,
'llma-prompt-duplicate': llmaPromptDuplicate,
'llma-prompt-get': llmaPromptGet,
+ 'llma-prompt-label-delete': llmaPromptLabelDelete,
+ 'llma-prompt-label-set': llmaPromptLabelSet,
'llma-prompt-list': llmaPromptList,
'llma-prompt-update': llmaPromptUpdate,
'llma-provider-key-get': llmaProviderKeyGet,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-delete.json
new file mode 100644
index 000000000000..93e6537f15c2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-delete.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "label_name": {
+ "pattern": "^[^/]+$",
+ "type": "string"
+ },
+ "prompt_name": {
+ "pattern": "^[^/]+$",
+ "type": "string"
+ }
+ },
+ "required": ["label_name", "prompt_name"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-set.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-set.json
new file mode 100644
index 000000000000..dcfbd221395d
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-label-set.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "label_name": {
+ "pattern": "^[^/]+$",
+ "type": "string"
+ },
+ "prompt_name": {
+ "pattern": "^[^/]+$",
+ "type": "string"
+ },
+ "version": {
+ "description": "Prompt version this label should point to. If the label already exists on another version of the prompt, it is moved there.",
+ "minimum": 1,
+ "type": "number"
+ }
+ },
+ "required": ["label_name", "prompt_name", "version"],
+ "type": "object"
+}