: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(llm-prompts): add prompt labels UI (#72266)
Juraj Majerik44fcade32ccf
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4105caf0094b..5839fc1371a4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -349,6 +349,7 @@ export const FEATURE_FLAGS = {LLM_ANALYTICS_TAGS: 'llm-analytics-tags', // owner: #team-ai-observabilityLLM_ANALYTICS_TRACE_NAVIGATION: 'llm-analytics-trace-navigation', // owner: #team-ai-observabilityLLM_OBSERVABILITY_TRACE_SEARCH: 'llm-observability-trace-search', // owner: #team-ai-observability+ LLM_PROMPT_LABELS: 'prompt-labels', // owner: @jurajmajerik #team-ai-observabilityLOGS: 'logs', // owner: #team-logsLOGS_ALERTING: 'logs-alerting', // owner: #team-logsLOGS_COLUMN_CONFIGURATION: 'logs-column-configuration', // owner: #team-logsdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex e5765f87ceae..43d7cc804388 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -78,6 +78,11 @@ import type {} from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'+import type {+ LLMPromptListApi,+ LLMPromptResolveResponseApi,+ LLMPromptVersionSummaryApi,+} from 'products/ai_observability/frontend/generated/api.schemas'import { AlertType } from 'products/alerts/frontend/types'import type { ExperimentFeatureFlagInputApi } from 'products/experiments/frontend/generated/api.schemas'import type { InsightFilterOverrideContextApi } from 'products/product_analytics/frontend/generated/api.schemas'@@ -7772,6 +7777,8 @@ export interface LLMPrompt {latest_version: numberversion_count: numberfirst_version_created_at: string+ /** All labels on the prompt with the version each points to. Only present on list responses. */+ all_labels?: LLMPromptListApi['all_labels']}export interface LLMPromptPublic {@@ -7795,12 +7802,14 @@ export interface LLMPromptVersionSummary {created_by: UserBasicTypecreated_at: stringis_latest: boolean+ labels?: LLMPromptVersionSummaryApi['labels']}export interface LLMPromptResolveResponse {prompt: LLMPromptversions: LLMPromptVersionSummary[]has_more: boolean+ labels: LLMPromptResolveResponseApi['labels']}// Managed viewsetdiff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.pyindex 6457ce6dde17..2a59406f2e20 100644--- a/posthog/api/llm_prompt.py+++ b/posthog/api/llm_prompt.py@@ -46,6 +46,7 @@ from posthog.api.services.llm_prompt import (get_active_prompt_queryset,get_latest_prompts_queryset,get_prompt_by_name_from_db,+ get_prompt_labels,publish_prompt_version,remove_prompt_label,resolve_versions_page,@@ -66,7 +67,7 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cachefrom products.ai_observability.backend.api.metrics import llma_track_latency-from products.ai_observability.backend.models.llm_prompt import LLMPrompt, get_prompt_outline+from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outlinePROMPT_FETCHED_EVENT = "$llm_prompt_fetched"PROMPT_FETCHED_EVENT_SOURCE = "llm_prompt_management"@@ -384,6 +385,7 @@ class LLMPromptViewSet("prompt": self._serialize_prompt(prompt),"versions": self._serialize_version_summaries(versions),"has_more": has_more,+ "labels": LLMPromptLabelSerializer(get_prompt_labels(self.team, prompt_name), many=True).data,})@@ -555,19 +557,32 @@ class LLMPromptViewSet()return Response(status=status.HTTP_204_NO_CONTENT)+ def _get_prompt_labels_map(self, prompt_names: list[str]) -> dict[str, list[dict[str, Any]]]:+ labels_map: dict[str, list[dict[str, Any]]] = {}+ labels = (+ LLMPromptLabel.objects.filter(team=self.team, prompt_name__in=prompt_names)+ .select_related("prompt")+ .order_by("prompt_name", "name")+ )+ for label in labels:+ labels_map.setdefault(label.prompt_name, []).append({"name": label.name, "version": label.prompt.version})+ return labels_map+@extend_schema(parameters=[LLMPromptListQuerySerializer])@llma_track_latency("llma_prompts_list")@monitor(feature=None, endpoint="llma_prompts_list", method="GET")def list(self, request: Request, *args, **kwargs) -> Response:queryset = self.filter_queryset(self._get_list_queryset(request))page = self.paginate_queryset(queryset)+ prompts = page if page is not None else list(queryset)++ context = self.get_serializer_context()+ context["prompt_labels_by_name"] = self._get_prompt_labels_map([prompt.name for prompt in prompts])+ serializer = LLMPromptListSerializer(prompts, many=True, context=context)+if page is not None:- serializer = self.get_serializer(page, many=True)return self.get_paginated_response(serializer.data)-- serializer = self.get_serializer(queryset, many=True)- data = serializer.data- return Response({"count": len(data), "results": data})+ return Response({"count": len(serializer.data), "results": serializer.data})@llma_track_latency("llma_prompts_create")@monitor(feature=None, endpoint="llma_prompts_create", method="POST")diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.pyindex cd0308d2cd7b..64d843c08e31 100644--- a/posthog/api/llm_prompt_serializers.py+++ b/posthog/api/llm_prompt_serializers.py@@ -362,17 +362,29 @@ class LLMPromptSerializer(serializers.ModelSerializer):)+class LLMPromptLabelSummarySerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Label name, e.g. 'production'.")+ version = serializers.IntegerField(help_text="Prompt version this label currently points to.")++class LLMPromptListSerializer(LLMPromptSerializer):prompt_size_bytes = serializers.SerializerMethodField()prompt_preview = serializers.SerializerMethodField()+ all_labels = serializers.SerializerMethodField()class Meta(LLMPromptSerializer.Meta):- fields = [*LLMPromptSerializer.Meta.fields, "prompt_preview", "prompt_size_bytes"]+ fields = [*LLMPromptSerializer.Meta.fields, "prompt_preview", "prompt_size_bytes", "all_labels"]read_only_fields = fieldsdef get_prompt_size_bytes(self, instance: LLMPrompt) -> int:return int(getattr(instance, "prompt_size_bytes", 0))+ @extend_schema_field(LLMPromptLabelSummarySerializer(many=True))+ def get_all_labels(self, instance: LLMPrompt) -> list[dict[str, Any]]:+ # The list queryset holds latest-version rows, whose own `labels` miss labels+ # pointing at older versions; the viewset injects the full per-prompt map.+ return self.context.get("prompt_labels_by_name", {}).get(instance.name, [])+def get_prompt_preview(self, instance: LLMPrompt) -> str:prompt = instance.promptdisplay_value = prompt if isinstance(prompt, str) else json.dumps(prompt, ensure_ascii=False)@@ -457,12 +469,6 @@ class LLMPromptDuplicateSerializer(serializers.Serializer):return validate_prompt_name_value(value)-class LLMPromptResolveResponseSerializer(serializers.Serializer):- prompt = LLMPromptSerializer()- versions = LLMPromptVersionSummarySerializer(many=True)- has_more = serializers.BooleanField()--class LLMPromptSetLabelSerializer(serializers.Serializer):version = serializers.IntegerField(min_value=1,@@ -496,3 +502,13 @@ class LLMPromptLabelSerializer(serializers.ModelSerializer):def get_version(self, instance: LLMPromptLabel) -> int:return instance.prompt.version+++class LLMPromptResolveResponseSerializer(serializers.Serializer):+ prompt = LLMPromptSerializer()+ versions = LLMPromptVersionSummarySerializer(many=True)+ has_more = serializers.BooleanField()+ labels = LLMPromptLabelSerializer(+ 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).",+ )diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.pyindex ccdfd729fcb3..6adc68bec0a5 100644--- a/posthog/api/services/llm_prompt.py+++ b/posthog/api/services/llm_prompt.py@@ -158,6 +158,14 @@ def resolve_versions_page(return versions[:limit], has_more+def get_prompt_labels(team: Team, prompt_name: str) -> QuerySet[LLMPromptLabel]:+ return (+ LLMPromptLabel.objects.filter(team=team, prompt_name=prompt_name)+ .select_related("prompt", "created_by")+ .order_by("name")+ )++def publish_prompt_version(team: Team,*,diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 9bdf7694bccb..30df36aacb9c 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -3,7 +3,9 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.db import connectionfrom django.test import SimpleTestCase, override_settings+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterizedfrom rest_framework import status@@ -1066,6 +1068,39 @@ class TestLLMPromptLabelsAPI(APIBaseTest):response = self.client.delete(self._label_url("my-prompt", "production"))assert response.status_code == status.HTTP_404_NOT_FOUND+ def test_resolve_returns_all_labels_including_versions_beyond_loaded_page(self):+ self.create_prompt_version(version=1, is_latest=False)+ self.create_prompt_version(version=2, is_latest=False)+ self.create_prompt_version(version=3)+ assert self._set_label("my-prompt", "production", 1).status_code == status.HTTP_201_CREATED++ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/my-prompt/?limit=1")++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert [entry["version"] for entry in data["versions"]] == [3]+ assert [(label["name"], label["version"]) for label in data["labels"]] == [("production", 1)]++ def test_list_all_labels_includes_labels_on_non_latest_versions_in_one_query(self):+ self.create_prompt_version(name="prompt-a", version=1, is_latest=False)+ self.create_prompt_version(name="prompt-a", version=2)+ self.create_prompt_version(name="prompt-b", version=1)+ assert self._set_label("prompt-a", "production", 1).status_code == status.HTTP_201_CREATED+ assert self._set_label("prompt-b", "staging", 1).status_code == status.HTTP_201_CREATED++ with CaptureQueriesContext(connection) as queries:+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/")++ assert response.status_code == status.HTTP_200_OK+ labels_by_prompt = {entry["name"]: entry["all_labels"] for entry in response.json()["results"]}+ assert labels_by_prompt == {+ "prompt-a": [{"name": "production", "version": 1}],+ "prompt-b": [{"name": "staging", "version": 1}],+ }+ # One batched all_labels query + one prefetch_related("labels") query — must not scale with prompt count.+ label_queries = [q for q in queries.captured_queries if "llmpromptlabel" in q["sql"].lower()]+ assert len(label_queries) == 2+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_CREATEDdiff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex ae7bd2899371..0c4a35abe8ba 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -2127,6 +2127,13 @@ export interface LLMPromptOutlineEntryApi {text: string}+export interface LLMPromptLabelSummaryApi {+ /** Label name, e.g. 'production'. */+ name: string+ /** Prompt version this label currently points to. */+ version: number+}+export interface LLMPromptListApi {readonly id: string/** Unique prompt name using letters, numbers, hyphens, and underscores only. */@@ -2152,6 +2159,7 @@ export interface LLMPromptListApi {readonly labels: readonly string[]readonly prompt_preview: stringreadonly prompt_size_bytes: number+ readonly all_labels: readonly LLMPromptLabelSummaryApi[]}export interface PaginatedLLMPromptListListApi {@@ -2281,6 +2289,8 @@ 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[]}/**diff --git a/products/ai_observability/frontend/prompts/LLMPromptsScene.tsx b/products/ai_observability/frontend/prompts/LLMPromptsScene.tsxindex d0ed5cec52fc..87e1f4a8a713 100644--- a/products/ai_observability/frontend/prompts/LLMPromptsScene.tsx+++ b/products/ai_observability/frontend/prompts/LLMPromptsScene.tsx@@ -7,9 +7,11 @@ import { Link } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { MemberSelect } from 'lib/components/MemberSelect'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { More } from 'lib/lemon-ui/LemonButton/More'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -22,6 +24,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, LLMPrompt } from '~/types'import { PROMPTS_PER_PAGE, llmPromptsLogic } from './llmPromptsLogic'+import { PromptLabelChip } from './PromptLabelChip'import { openArchivePromptDialog, openDuplicatePromptDialog } from './utils'export const scene: SceneExport = {@@ -36,6 +39,8 @@ export function LLMPromptsScene(): JSX.Element {const { prompts, promptsLoading, sorting, pagination, filters, promptCountLabel, shouldShowEmptyState } =useValues(llmPromptsLogic)const { searchParams } = useValues(router)+ const { featureFlags } = useValues(featureFlagLogic)+ const labelsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_PROMPT_LABELS]const promptUrl = (name: string): string => combineUrl(urls.aiObservabilityPrompt(name), searchParams).urlconst columns: LemonTableColumns<LLMPrompt> = [@@ -86,6 +91,26 @@ export function LLMPromptsScene(): JSX.Element {return <span className="text-muted-alt">{prompt.version_count}</span>},},+ ...(labelsEnabled+ ? ([+ {+ title: 'Labels',+ key: 'labels',+ render: function renderLabels(_, prompt) {+ if (!prompt.all_labels?.length) {+ return <span className="text-muted-alt">–</span>+ }+ return (+ <div className="flex flex-wrap gap-1">+ {prompt.all_labels.map((label) => (+ <PromptLabelChip key={label.name} label={`${label.name}: v${label.version}`} />+ ))}+ </div>+ )+ },+ },+ ] as LemonTableColumns<LLMPrompt>)+ : []),atColumn('created_at', 'Latest version created') as LemonTableColumn<LLMPrompt, keyof LLMPrompt | undefined>,{width: 0,diff --git a/products/ai_observability/frontend/prompts/PromptLabelChip.tsx b/products/ai_observability/frontend/prompts/PromptLabelChip.tsxnew file mode 100644index 000000000000..d8216ff2a297--- /dev/null+++ b/products/ai_observability/frontend/prompts/PromptLabelChip.tsx@@ -0,0 +1,56 @@+import { IconX } from '@posthog/icons'++// A removable token, not a status badge: one box owns all spacing (the X is a glyph+// in the text flow, not a nested button component), fixed height on the 4px grid,+// optically lighter padding on the icon side.+// `disabledReason` follows the AccessControlAction contract so the chip can be+// wrapped in the same Editor gate as the other prompt actions.+export function PromptLabelChip({+ label,+ onRemove,+ disabledReason,+ 'data-attr': dataAttr,+}: {+ label: string+ onRemove?: () => void+ disabled?: boolean+ disabledReason?: string | null+ 'data-attr'?: string+}): JSX.Element {+ return (+ <span+ className={`inline-flex h-5 items-center gap-1 whitespace-nowrap rounded-[var(--radius)] border border-[color-mix(in_srgb,var(--purple)_35%,transparent)] bg-[color-mix(in_srgb,var(--purple)_10%,transparent)] pl-2 text-[11px] font-medium text-purple ${+ onRemove ? 'pr-1' : 'pr-2'+ }`}+ data-attr={dataAttr}+ >+ {/* Labels can be up to 128 characters; truncate so the remove button stays reachable. */}+ <span className="max-w-40 truncate" title={label}>+ {label}+ </span>+ {onRemove ? (+ <button+ type="button"+ aria-label={`Remove label ${label}`}+ aria-disabled={disabledReason ? true : undefined}+ title={disabledReason ?? undefined}+ className={`grid size-3.5 shrink-0 place-items-center rounded-[calc(var(--radius)-2px)] ${+ disabledReason+ ? 'cursor-not-allowed opacity-30'+ : 'cursor-pointer opacity-60 hover:bg-[color-mix(in_srgb,var(--purple)_20%,transparent)] hover:opacity-100'+ }`}+ onClick={(e) => {+ // Chips render inside Link-wrapped cards; removing must not navigate.+ e.preventDefault()+ e.stopPropagation()+ if (!disabledReason) {+ onRemove()+ }+ }}+ >+ <IconX className="size-3" />+ </button>+ ) : null}+ </span>+ )+}diff --git a/products/ai_observability/frontend/prompts/PromptLabelPicker.tsx b/products/ai_observability/frontend/prompts/PromptLabelPicker.tsxnew file mode 100644index 000000000000..0ebd0f5b503d--- /dev/null+++ b/products/ai_observability/frontend/prompts/PromptLabelPicker.tsx@@ -0,0 +1,88 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList } from 'lib/ui/quill'++import { llmPromptLogic } from './llmPromptLogic'+import { validatePromptLabelName } from './utils'++const CREATE_SENTINEL_PREFIX = '__create__:'++export function PromptLabelPicker({ version }: { version: number }): JSX.Element {+ const { promptLabels } = useValues(llmPromptLogic)+ const { requestSetLabel, closeLabelPicker } = useActions(llmPromptLogic)+ const [inputValue, setInputValue] = useState('')++ const trimmed = inputValue.trim()+ const existingNames = promptLabels.map((label) => label.name)+ const validationError = trimmed ? validatePromptLabelName(trimmed) : undefined++ const items: string[] = [...existingNames]+ if (existingNames.length === 0 && !trimmed) {+ items.push('production')+ }+ const createSentinel = `${CREATE_SENTINEL_PREFIX}${trimmed}`+ const showCreateItem = trimmed.length > 0 && !existingNames.includes(trimmed) && !validationError+ if (showCreateItem) {+ items.push(createSentinel)+ }++ const labelHint = (name: string): string | null => {+ const label = promptLabels.find((l) => l.name === name)+ if (!label) {+ return null+ }+ return label.version === version ? 'already on this version' : `currently on v${label.version}`+ }++ return (+ <Combobox+ autoHighlight+ items={items}+ value={null}+ onValueChange={(next: string | null) => {+ if (!next) {+ return+ }+ const name = next.startsWith(CREATE_SENTINEL_PREFIX) ? next.slice(CREATE_SENTINEL_PREFIX.length) : next+ requestSetLabel(name, version)+ }}+ inputValue={inputValue}+ onInputValueChange={(value: string) => setInputValue(value)}+ defaultOpen+ onOpenChange={(open: boolean) => {+ if (!open) {+ closeLabelPicker()+ }+ }}+ >+ <ComboboxInput+ placeholder="Label name"+ autoFocus+ showTrigger={false}+ data-attr="llma-prompt-label-picker-input"+ />+ <ComboboxContent>+ <ComboboxEmpty>{validationError ?? 'No matching labels'}</ComboboxEmpty>+ <ComboboxList>+ {(item: string) => {+ if (item === createSentinel) {+ return (+ <ComboboxItem key={item} value={item}>+ Create label "{trimmed}"+ </ComboboxItem>+ )+ }+ const hint = labelHint(item)+ return (+ <ComboboxItem key={item} value={item}>+ <span>{item}</span>+ {hint ? <span className="text-xs text-secondary">{hint}</span> : null}+ </ComboboxItem>+ )+ }}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+}diff --git a/products/ai_observability/frontend/prompts/llmPromptLogic.test.ts b/products/ai_observability/frontend/prompts/llmPromptLogic.test.tsindex 23a7251e10b0..ec6fe7b0100e 100644--- a/products/ai_observability/frontend/prompts/llmPromptLogic.test.ts+++ b/products/ai_observability/frontend/prompts/llmPromptLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'@@ -5,11 +7,22 @@ import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import api from '~/lib/api'import { ApiError } from '~/lib/api-error'+import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'import { EventsQuery, NodeKind, TracesQuery } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { LLMPrompt, LLMPromptResolveResponse, PropertyFilterType, PropertyOperator } from '~/types'+import { llmPromptsNameLabelsDestroy, llmPromptsNameLabelsUpdate } from '../generated/api'import { PromptAnalyticsScope, PromptMode, llmPromptLogic } from './llmPromptLogic'+import { validatePromptLabelName } from './utils'++jest.mock('../generated/api', () => ({+ llmPromptsNameLabelsUpdate: jest.fn(),+ llmPromptsNameLabelsDestroy: jest.fn(),+}))++const mockLabelsUpdate = llmPromptsNameLabelsUpdate as jest.MockedFunction<typeof llmPromptsNameLabelsUpdate>+const mockLabelsDestroy = llmPromptsNameLabelsDestroy as jest.MockedFunction<typeof llmPromptsNameLabelsDestroy>const mockPrompt = {id: 'prompt-version-2',@@ -43,11 +56,33 @@ const mockPrompt = {has_more: false,}+const productionLabelV1 = {+ id: 'label-1',+ name: 'production',+ prompt_name: 'my-test-prompt',+ version: 1,+ created_by: { id: 1, email: '[email protected]' },+ created_at: '2024-01-02T00:00:00Z',+ updated_at: '2024-01-02T00:00:00Z',+}+describe('llmPromptLogic', () => {beforeEach(() => {initKeaTests()+ jest.clearAllMocks()})+ function mountWithLabels(): ReturnType<typeof llmPromptLogic.build> {+ const { versions, has_more, ...promptFields } = mockPrompt+ jest.spyOn(api.llmPrompts, 'resolveByName').mockResolvedValue({+ prompt: promptFields,+ versions,+ has_more,+ labels: [productionLabelV1],+ } as unknown as LLMPromptResolveResponse)+ return llmPromptLogic({ promptName: 'my-test-prompt' })+ }+it('defaults to view mode for existing prompts', async () => {const logic = llmPromptLogic({ promptName: 'existing-prompt' })logic.mount()@@ -392,6 +427,84 @@ describe('llmPromptLogic', () => {logic.unmount()})+ it('moving a label requires confirmation and replaces its previous position', async () => {+ const dialogSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const logic = mountWithLabels()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPromptSuccess'])+ expect(logic.values.labelsByVersion).toEqual({ 1: [expect.objectContaining({ name: 'production' })] })++ logic.actions.requestSetLabel('production', 2)++ expect(dialogSpy).toHaveBeenCalledTimes(1)+ expect(mockLabelsUpdate).not.toHaveBeenCalled()++ mockLabelsUpdate.mockResolvedValue({ ...productionLabelV1, version: 2 } as any)+ await dialogSpy.mock.calls[0][0].primaryButton?.onClick?.(undefined as any)++ expect(mockLabelsUpdate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'my-test-prompt', 'production', {+ version: 2,+ })+ expect(logic.values.labelsByVersion).toEqual({+ 2: [expect.objectContaining({ name: 'production', version: 2 })],+ })++ logic.unmount()+ })++ it('keeps labels unchanged and resyncs after losing a concurrent label write', async () => {+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')+ const dialogSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const logic = mountWithLabels()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPromptSuccess'])++ mockLabelsUpdate.mockRejectedValue(+ new ApiError('conflict', 409, undefined, {+ detail: 'This label was changed by someone else at the same time. Try again.',+ })+ )+ logic.actions.requestSetLabel('staging', 2)+ // Creating a new label also requires confirmation (code may already fetch by it).+ expect(dialogSpy).toHaveBeenCalledTimes(1)+ expect(mockLabelsUpdate).not.toHaveBeenCalled()+ await dialogSpy.mock.calls[0][0].primaryButton?.onClick?.(undefined as any)+ await expectLogic(logic).toDispatchActions(['setLabel', 'loadPrompt', 'loadPromptSuccess'])++ expect(toastSpy).toHaveBeenCalled()+ expect(logic.values.labelsByVersion).toEqual({ 1: [expect.objectContaining({ name: 'production' })] })++ logic.unmount()+ })++ it('keeps a label visible when its delete request fails', async () => {+ const dialogSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')+ const logic = mountWithLabels()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPromptSuccess'])++ mockLabelsDestroy.mockRejectedValue(new ApiError('server error', 500))+ logic.actions.requestRemoveLabel('production')+ expect(dialogSpy).toHaveBeenCalledTimes(1)++ await dialogSpy.mock.calls[0][0].primaryButton?.onClick?.(undefined as any)++ expect(logic.values.labelsByVersion).toEqual({ 1: [expect.objectContaining({ name: 'production' })] })++ logic.unmount()+ })++ // One row per validation rule: allowlisted characters, reserved name, digits-only, lowercase-only.+ it.each([+ ['release-2.1_final', true],+ ['latest', false],+ ['123', false],+ ['Production', false],+ ])('validatePromptLabelName(%s) accepts=%s', (name, accepted) => {+ expect(validatePromptLabelName(name) === undefined).toBe(accepted)+ })+it('resets new prompt form values after unmount and remount', async () => {const firstMount = llmPromptLogic({ promptName: 'new' })firstMount.mount()diff --git a/products/ai_observability/frontend/prompts/llmPromptLogic.ts b/products/ai_observability/frontend/prompts/llmPromptLogic.tsindex cda1fb74204d..971cd2e9858f 100644--- a/products/ai_observability/frontend/prompts/llmPromptLogic.ts+++ b/products/ai_observability/frontend/prompts/llmPromptLogic.ts@@ -18,7 +18,7 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } fromimport { loaders } from 'kea-loaders'import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'-import api, { ApiError } from '~/lib/api'+import api, { ApiConfig, ApiError } from '~/lib/api'import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'import {@@ -44,9 +44,19 @@ import {} from '~/types'import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'+import { llmPromptsNameLabelsDestroy, llmPromptsNameLabelsUpdate } from '../generated/api'+import type { LLMPromptLabelApi } from '../generated/api.schemas'import { llmPromptsLogic } from './llmPromptsLogic'import { LLM_PROMPTS_FORCE_RELOAD_PARAM } from './llmPromptsLogic'-import { getApiErrorDetail, openDiscardChangesDialog, requestPromptDuplicate, validatePromptName } from './utils'+import {+ getApiErrorDetail,+ openCreateLabelDialog,+ openDiscardChangesDialog,+ openMoveLabelDialog,+ openRemoveLabelDialog,+ requestPromptDuplicate,+ validatePromptName,+} from './utils'export enum PromptMode {View = 'view',@@ -72,6 +82,7 @@ export interface PromptFormValues {export interface ResolvedLLMPrompt extends LLMPrompt {versions: LLMPromptVersionSummary[]has_more: boolean+ labels: LLMPromptLabelApi[]}export function isPrompt(prompt: LLMPrompt | ResolvedLLMPrompt | PromptFormValues | null): prompt is ResolvedLLMPrompt {@@ -122,6 +133,7 @@ function getResolvedPrompt(response: LLMPromptResolveResponse): ResolvedLLMPromp...response.prompt,versions: response.versions,has_more: response.has_more,+ labels: response.labels ?? [],}}@@ -173,6 +185,8 @@ export interface llmPromptLogicValues {isPublishReviewOpen: booleanisRenderingMarkdown: booleanisViewMode: boolean+ labelPickerVersion: number | null+ labelsByVersion: Record<number, LLMPromptLabelApi[]>mode: PromptModenextVersion: number | nullprompt: PromptFormValues | ResolvedLLMPrompt | null@@ -185,6 +199,7 @@ export interface llmPromptLogicValues {promptFormTouched: booleanpromptFormTouches: Record<string, boolean>promptFormValidationErrors: DeepPartialMap<PromptFormValues, ValidationErrorType>+ promptLabels: LLMPromptLabelApi[]promptLoading: booleanpromptUsageLogQuery: DataTableNodepromptUsagePropertyFilter: AnyPropertyFilter[]@@ -209,6 +224,9 @@ export interface llmPromptLogicActions {cancelEditing: () => {value: true}+ closeLabelPicker: () => {+ value: true+ }closePublishReview: () => {value: true}@@ -255,12 +273,28 @@ export interface llmPromptLogicActions {prompt: ResolvedLLMPromptpayload?: any}+ openLabelPicker: (version: number) => {+ version: number+ }openPublishReview: () => {value: true}+ removeLabel: (labelName: string) => {+ labelName: string+ }requestPublish: () => {value: true}+ requestRemoveLabel: (labelName: string) => {+ labelName: string+ }+ requestSetLabel: (+ labelName: string,+ version: number+ ) => {+ labelName: string+ version: number+ }resetPromptForm: (values?: PromptFormValues) => {values?: PromptFormValues}@@ -270,6 +304,13 @@ export interface llmPromptLogicActions {setCompareVersion: (compareVersion: number | null) => {compareVersion: number | null}+ setLabel: (+ labelName: string,+ version: number+ ) => {+ labelName: string+ version: number+ }setMode: (mode: PromptMode) => {mode: PromptMode}@@ -354,6 +395,8 @@ export interface llmPromptLogicMeta {isEditMode: (mode: PromptMode, arg: any) => booleanversions: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => LLMPromptVersionSummary[]canLoadMoreVersions: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => boolean+ promptLabels: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => LLMPromptLabelApi[]+ labelsByVersion: (promptLabels: LLMPromptLabelApi[]) => Record<number, LLMPromptLabelApi[]>isDiffVisible: (compareVersion: number | null) => booleancanCompareVersions: (prompt: PromptFormValues | ResolvedLLMPrompt | null) => booleancompareVersionOptions: (@@ -431,6 +474,12 @@ export const llmPromptLogic = kea<llmPromptLogicType>([closePublishReview: true,setVersionDescription: (versionDescription: string) => ({ versionDescription }),setSnippetLanguage: (snippetLanguage: PromptSnippetLanguage) => ({ snippetLanguage }),+ openLabelPicker: (version: number) => ({ version }),+ closeLabelPicker: true,+ requestSetLabel: (labelName: string, version: number) => ({ labelName, version }),+ setLabel: (labelName: string, version: number) => ({ labelName, version }),+ requestRemoveLabel: (labelName: string) => ({ labelName }),+ removeLabel: (labelName: string) => ({ labelName }),}),reducers(({ props }) => ({@@ -528,6 +577,15 @@ export const llmPromptLogic = kea<llmPromptLogicType>([setSnippetLanguage: (_, { snippetLanguage }) => snippetLanguage,},],+ labelPickerVersion: [+ null as number | null,+ {+ openLabelPicker: (_, { version }) => version,+ closeLabelPicker: () => null,+ requestSetLabel: () => null,+ loadPromptSuccess: () => null,+ },+ ],})),loaders(({ props }) => ({@@ -603,6 +661,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([...savedPrompt,versions: optimisticVersions,has_more: currentPrompt.has_more,+ labels: currentPrompt.labels,})actions.setPromptFormValues(getPromptFormDefaults(savedPrompt))actions.setMode(PromptMode.View)@@ -620,6 +679,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([...savedPrompt,versions: [],has_more: false,+ labels: [],})actions.setPromptFormValues(getPromptFormDefaults(savedPrompt))}@@ -747,6 +807,23 @@ export const llmPromptLogic = kea<llmPromptLogicType>([(prompt: PromptFormValues | ResolvedLLMPrompt | null) => (isPrompt(prompt) ? prompt.has_more : false),],+ promptLabels: [+ (s) => [s.prompt],+ (prompt: PromptFormValues | ResolvedLLMPrompt | null): LLMPromptLabelApi[] =>+ isPrompt(prompt) ? (prompt.labels ?? []) : [],+ ],++ labelsByVersion: [+ (s) => [s.promptLabels],+ (promptLabels: LLMPromptLabelApi[]): Record<number, LLMPromptLabelApi[]> => {+ const byVersion: Record<number, LLMPromptLabelApi[]> = {}+ for (const label of promptLabels) {+ byVersion[label.version] = [...(byVersion[label.version] ?? []), label]+ }+ return byVersion+ },+ ],+isDiffVisible: [(s) => [s.compareVersion], (compareVersion: number | null): boolean => compareVersion !== null],canCompareVersions: [@@ -1006,7 +1083,89 @@ export const llmPromptLogic = kea<llmPromptLogicType>([],}),- listeners(({ actions, props, values }) => ({+ listeners(({ actions, asyncActions, props, values }) => ({+ requestSetLabel: ({ labelName, version }) => {+ const existing = values.promptLabels.find((label) => label.name === labelName)+ if (existing?.version === version) {+ return+ }+ if (existing) {+ openMoveLabelDialog({+ labelName,+ fromVersion: existing.version,+ toVersion: version,+ onMove: () => asyncActions.setLabel(labelName, version),+ })+ return+ }+ // Creation confirms too: code may already fetch by this label (404 → SDK fallback),+ // in which case creating it is the go-live moment.+ openCreateLabelDialog({+ labelName,+ version,+ onCreate: () => asyncActions.setLabel(labelName, version),+ })+ },++ // Never throws: kea surfaces a throwing listener as an unhandled rejection. The awaited+ // dialog button resolves either way; errors surface via toast.+ setLabel: async ({ labelName, version }) => {+ try {+ const label = await llmPromptsNameLabelsUpdate(+ String(ApiConfig.getCurrentTeamId()),+ props.promptName,+ labelName,+ { version }+ )+ if (isPrompt(values.prompt)) {+ actions.setPrompt({+ ...values.prompt,+ labels: [...values.prompt.labels.filter((l) => l.name !== labelName), label],+ })+ }+ lemonToast.success(`${labelName} now points at v${version}`)+ llmPromptsLogic.findMounted()?.actions.loadPrompts(false)+ } catch (error) {+ lemonToast.error(getApiErrorDetail(error) || 'Failed to set label')+ if (error instanceof ApiError && error.status === 409) {+ // Lost a concurrent-write race; resync so badges show where the label actually is.+ actions.loadPrompt()+ }+ }+ },++ requestRemoveLabel: ({ labelName }) => {+ const existing = values.promptLabels.find((label) => label.name === labelName)+ if (!existing) {+ return+ }+ openRemoveLabelDialog({+ labelName,+ version: existing.version,+ onRemove: () => asyncActions.removeLabel(labelName),+ })+ },++ removeLabel: async ({ labelName }) => {+ try {+ await llmPromptsNameLabelsDestroy(String(ApiConfig.getCurrentTeamId()), props.promptName, labelName)+ } catch (error) {+ // 404 means the label is already gone; reflect that locally like a success.+ if (!(error instanceof ApiError && error.status === 404)) {+ lemonToast.error(getApiErrorDetail(error) || 'Failed to remove label')+ return+ }+ }+ if (isPrompt(values.prompt)) {+ actions.setPrompt({+ ...values.prompt,+ labels: values.prompt.labels.filter((l) => l.name !== labelName),+ })+ }+ lemonToast.info(`Label ${labelName} removed`)+ llmPromptsLogic.findMounted()?.actions.loadPrompts(false)+ },+requestPublish: () => {// New prompts publish directly (v1, nothing to diff against); an empty form// goes through submit so kea-forms surfaces the validation errors.@@ -1128,7 +1287,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([if (existingPrompt) {return {- prompt: { ...existingPrompt, versions: [], has_more: false },+ prompt: { ...existingPrompt, versions: [], has_more: false, labels: [] },promptForm: getPromptFormDefaults(existingPrompt),versionsLoading: false,}diff --git a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx b/products/ai_observability/frontend/prompts/promptSceneComponents.tsxindex c51f3c4c6135..1a09627add67 100644--- a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx+++ b/products/ai_observability/frontend/prompts/promptSceneComponents.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'import { Suspense, useRef } from 'react'-import { IconColumns, IconMarkdown, IconMarkdownFilled } from '@posthog/icons'+import { IconColumns, IconMarkdown, IconMarkdownFilled, IconPlusSmall } from '@posthog/icons'import {LemonBanner,LemonButton,@@ -16,6 +16,7 @@ import {import { AccessControlAction } from 'lib/components/AccessControlAction'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'@@ -24,6 +25,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { lazyWithRetry } from 'lib/utils/retryImport'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -39,6 +41,8 @@ import { CreatePromptExperimentModal } from './CreatePromptExperimentModal'import { createPromptExperimentModalLogic } from './createPromptExperimentModalLogic'import { PromptAnalyticsScope, isPrompt, llmPromptLogic } from './llmPromptLogic'import { promptExperimentsLogic } from './promptExperimentsLogic'+import { PromptLabelChip } from './PromptLabelChip'+import { PromptLabelPicker } from './PromptLabelPicker'import { PROMPT_NAME_MAX_LENGTH } from './utils'const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))@@ -791,8 +795,10 @@ export function PromptVersionSidebar({searchParams: Record<string, any>readOnly?: boolean}): JSX.Element {- const { compareVersion } = useValues(llmPromptLogic)- const { setCompareVersion } = useActions(llmPromptLogic)+ const { compareVersion, labelsByVersion, labelPickerVersion } = useValues(llmPromptLogic)+ const { setCompareVersion, openLabelPicker, requestRemoveLabel } = useActions(llmPromptLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const labelsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_PROMPT_LABELS]return (<aside className="w-full shrink-0 xl:sticky xl:top-4 xl:mt-3 xl:w-80">@@ -862,6 +868,52 @@ export function PromptVersionSidebar({{versionPrompt.created_by?.email ? (<div className="mt-1 text-xs text-secondary">{versionPrompt.created_by.email}</div>) : null}+ {labelsEnabled ? (+ <div+ className="mt-1.5 flex flex-wrap items-center gap-1"+ // The card is a Link; label actions must not navigate. Capture-phase+ // preventDefault runs before child handlers that stopPropagation+ // (e.g. LemonTag's close button), which would otherwise let the+ // anchor's native navigation through.+ onClickCapture={(e) => e.preventDefault()}+ onClick={(e) => e.stopPropagation()}+ >+ {(labelsByVersion[versionPrompt.version] ?? []).map((label) => (+ <AccessControlAction+ key={label.name}+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <PromptLabelChip+ label={label.name}+ onRemove={+ readOnly ? undefined : () => requestRemoveLabel(label.name)+ }+ data-attr={`llma-prompt-label-${label.name}`}+ />+ </AccessControlAction>+ ))}+ {!readOnly &&+ (labelPickerVersion === versionPrompt.version ? (+ <PromptLabelPicker version={versionPrompt.version} />+ ) : (+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="xsmall"+ icon={<IconPlusSmall />}+ onClick={() => openLabelPicker(versionPrompt.version)}+ tooltip="Point a label at this version"+ data-attr={`llma-prompt-add-label-${versionPrompt.version}`}+ >+ Add label+ </LemonButton>+ </AccessControlAction>+ ))}+ </div>+ ) : null}</>)diff --git a/products/ai_observability/frontend/prompts/utils.tsx b/products/ai_observability/frontend/prompts/utils.tsxindex 0eabbe6bff4d..4724a3ebeb6b 100644--- a/products/ai_observability/frontend/prompts/utils.tsx+++ b/products/ai_observability/frontend/prompts/utils.tsx@@ -26,6 +26,108 @@ export function validatePromptName(name: string | undefined): string | undefinedreturn undefined}+export const PROMPT_LABEL_MAX_LENGTH = 128+// Mirrors validate_prompt_label_name_value in posthog/api/llm_prompt_serializers.py; the backend stays authoritative.+const PROMPT_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/++export function validatePromptLabelName(name: string): string | undefined {+ const trimmed = name.trim()+ if (!trimmed) {+ return 'Label name is required'+ }+ if (trimmed.toLowerCase() === 'latest') {+ return "'latest' is reserved and cannot be used as a label"+ }+ if (/^[0-9]+$/.test(trimmed)) {+ return 'Label names cannot be numbers only, to avoid confusion with version numbers'+ }+ if (trimmed.length > PROMPT_LABEL_MAX_LENGTH) {+ return `Label must be ${PROMPT_LABEL_MAX_LENGTH} characters or fewer`+ }+ if (!PROMPT_LABEL_PATTERN.test(trimmed)) {+ return 'Use lowercase letters, numbers, dots (.), hyphens (-) and underscores (_), starting and ending with a letter or number'+ }+ return undefined+}++export function openCreateLabelDialog({+ labelName,+ version,+ onCreate,+}: {+ labelName: string+ version: number+ onCreate: () => Promise<void>+}): void {+ LemonDialog.open({+ title: 'Create label?',+ description: `${labelName} → v${version}. Anything fetching this prompt by this label starts resolving v${version} within seconds.`,+ shouldAwaitSubmit: true,+ primaryButton: {+ children: 'Create',+ type: 'primary',+ onClick: onCreate,+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'secondary',+ },+ })+}++export function openMoveLabelDialog({+ labelName,+ fromVersion,+ toVersion,+ onMove,+}: {+ labelName: string+ fromVersion: number+ toVersion: number+ onMove: () => Promise<void>+}): void {+ LemonDialog.open({+ title: 'Move label?',+ description: `${labelName}: v${fromVersion} → v${toVersion}. Anything fetching this prompt by this label picks up the change within seconds.`,+ shouldAwaitSubmit: true,+ primaryButton: {+ children: 'Move',+ type: 'primary',+ onClick: onMove,+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'secondary',+ },+ })+}++export function openRemoveLabelDialog({+ labelName,+ version,+ onRemove,+}: {+ labelName: string+ version: number+ onRemove: () => Promise<void>+}): void {+ LemonDialog.open({+ title: 'Remove label?',+ description: `${labelName} currently points at v${version}. Any code fetching this prompt by this label will stop resolving it.`,+ shouldAwaitSubmit: true,+ primaryButton: {+ children: 'Remove',+ type: 'primary',+ status: 'danger',+ onClick: onRemove,+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'secondary',+ },+ })+}+export function getApiErrorDetail(error: unknown): string | undefined {if (error !== null && typeof error === 'object' && 'detail' in error && typeof error.detail === 'string') {return error.detaildiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 80ef64fca906..14c809d9d849 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34059,6 +34059,13 @@ export namespace Schemas {readonly updated_at: string;}+ export interface LLMPromptLabelSummary {+ /** Label name, e.g. 'production'. */+ name: string;+ /** Prompt version this label currently points to. */+ version: number;+ }+export interface LLMPromptList {readonly id: string;/** Unique prompt name using letters, numbers, hyphens, and underscores only. */@@ -34084,6 +34091,7 @@ export namespace Schemas {readonly labels: readonly string[];readonly prompt_preview: string;readonly prompt_size_bytes: number;+ readonly all_labels: readonly LLMPromptLabelSummary[];}export interface LLMPromptPublic {@@ -34123,6 +34131,8 @@ export namespace Schemas {prompt: LLMPrompt;versions: LLMPromptVersionSummary[];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[];}export interface LLMPromptSetLabel {