: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): surface label activity in a prompt history tab (#72811)
Juraj Majerikd302b850808c
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e6960e93cedd..4de74c7edb74 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2687,6 +2687,7 @@ const api = {ActivityScope.COHORT,ActivityScope.OAUTH_APPLICATION,ActivityScope.EXTERNAL_DATA_SCHEMA,+ ActivityScope.LLM_PROMPT_LABEL,].includes(scopes[0]) ||scopes.length > 1) {diff --git a/frontend/src/lib/components/ActivityLog/describers.tsx b/frontend/src/lib/components/ActivityLog/describers.tsxindex 5699e9abdfe6..7739225f1680 100644--- a/frontend/src/lib/components/ActivityLog/describers.tsx+++ b/frontend/src/lib/components/ActivityLog/describers.tsx@@ -38,6 +38,7 @@ import { teamActivityDescriber } from 'scenes/team-activity/teamActivityDescribeimport { ActivityScope } from '~/types'+import { promptLabelActivityDescriber } from 'products/ai_observability/frontend/prompts/promptLabelActivityDescriber'import { alertConfigurationActivityDescriber } from 'products/alerts/frontend/components/activityDescriptions'import { ticketActivityDescriber } from 'products/conversations/frontend/activityDescriber'import { externalDataSourceActivityDescriber } from 'products/data_warehouse/frontend/shared/components/activityDescriptions'@@ -129,6 +130,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =return ticketActivityDescribercase ActivityScope.SIGNAL_SCOUT_CONFIG:return signalScoutConfigActivityDescriber+ case ActivityScope.LLM_PROMPT_LABEL:+ return promptLabelActivityDescriberdefault:return defaultDescriber}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 603801fc7fe0..0cbc78a99a5c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -80,6 +80,7 @@ import type {import { QueryContext } from '~/queries/types'import type {+ LLMPromptApi,LLMPromptListApi,LLMPromptResolveResponseApi,LLMPromptVersionSummaryApi,@@ -5983,6 +5984,7 @@ export enum ActivityScope {ENDPOINT_VERSION = 'EndpointVersion',HEATMAP = 'Heatmap',USER = 'User',+ LLM_PROMPT_LABEL = 'LLMPromptLabel',LLM_TRACE = 'LLMTrace',LOG = 'Log',LOGS_ALERT_CONFIGURATION = 'LogsAlertConfiguration',@@ -7793,6 +7795,8 @@ export interface LLMPrompt {latest_version: numberversion_count: numberfirst_version_created_at: string+ /** Key for this prompt's rows in the activity log (History tab). */+ activity_item_id: LLMPromptApi['activity_item_id']/** All labels on the prompt with the version each points to. Only present on list responses. */all_labels?: LLMPromptListApi['all_labels']}diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.pyindex 64d843c08e31..ec937c6a053f 100644--- a/posthog/api/llm_prompt_serializers.py+++ b/posthog/api/llm_prompt_serializers.py@@ -7,6 +7,7 @@ from rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer+from products.ai_observability.backend.activity_logging import prompt_activity_item_idfrom products.ai_observability.backend.models.llm_prompt import (LLMPrompt,LLMPromptLabel,@@ -238,6 +239,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):first_version_created_at = serializers.SerializerMethodField()outline = serializers.SerializerMethodField()labels = serializers.SerializerMethodField()+ activity_item_id = serializers.SerializerMethodField()class Meta:model = LLMPrompt@@ -257,6 +259,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):"first_version_created_at","outline","labels",+ "activity_item_id",]read_only_fields = ["id",@@ -271,6 +274,7 @@ class LLMPromptSerializer(serializers.ModelSerializer):"first_version_created_at","outline","labels",+ "activity_item_id",]extra_kwargs = {"name": {"help_text": "Unique prompt name using letters, numbers, hyphens, and underscores only."},@@ -284,6 +288,14 @@ class LLMPromptSerializer(serializers.ModelSerializer):def get_outline(self, instance: LLMPrompt) -> list[dict[str, Any]]:return get_prompt_outline(instance.prompt)+ @extend_schema_field(+ serializers.CharField(+ help_text="Key for this prompt's rows in the activity log, e.g. for the History tab. Derived from the name, at most 72 characters."+ )+ )+ def get_activity_item_id(self, instance: LLMPrompt) -> str:+ return prompt_activity_item_id(instance.name)+@extend_schema_field(serializers.ListField(child=serializers.CharField(),diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.pyindex 30df36aacb9c..ce35d9dadd71 100644--- a/posthog/api/test/test_llm_prompt.py+++ b/posthog/api/test/test_llm_prompt.py@@ -1195,6 +1195,8 @@ class TestLLMPromptLabelsAPI(APIBaseTest):entries = list(ActivityLog.objects.filter(team_id=self.team.id, scope="LLMPromptLabel").order_by("created_at"))assert [entry.activity for entry in entries] == ["created", "updated", "deleted"]+ # item_id is the prompt name: the prompt page History tab queries by it.+ assert all(entry.item_id == "my-prompt" for entry in entries)move_detail = entries[1].detailassert move_detail is not Noneassert move_detail["name"] == "my-prompt: production"@@ -1202,6 +1204,32 @@ class TestLLMPromptLabelsAPI(APIBaseTest):assert move_detail["changes"][0]["after"] == 2assert entries[1].user is not None and entries[1].user.id == self.user.id+ def test_label_activity_survives_prompt_names_longer_than_item_id_column(self):+ long_name = "a" * 100 # valid prompt name (max 255) but longer than ActivityLog.item_id's varchar(72)+ self.create_prompt_version(name=long_name, version=1)++ response = self._set_label(long_name, "production", 1)++ assert response.status_code == status.HTTP_201_CREATED+ entry = ActivityLog.objects.get(team_id=self.team.id, scope="LLMPromptLabel")+ assert entry.item_id == "a" * 39 + "#2816597888e4a0d3a36b82b83316ab32"+ # The History tab queries by the serializer-provided key; it must match what was logged.+ resolve = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/resolve/name/{long_name}/")+ assert resolve.json()["prompt"]["activity_item_id"] == entry.item_id++ def test_long_prompt_names_sharing_a_prefix_get_distinct_activity_keys(self):+ shared_prefix = "b" * 80+ self.create_prompt_version(name=shared_prefix + "-one", version=1)+ self.create_prompt_version(name=shared_prefix + "-two", version=1)++ assert self._set_label(shared_prefix + "-one", "production", 1).status_code == status.HTTP_201_CREATED+ assert self._set_label(shared_prefix + "-two", "production", 1).status_code == status.HTTP_201_CREATED++ item_ids = set(+ ActivityLog.objects.filter(team_id=self.team.id, scope="LLMPromptLabel").values_list("item_id", flat=True)+ )+ assert len(item_ids) == 2+def test_archive_logs_label_deletion(self):self.create_prompt_version(version=1)self._set_label("my-prompt", "production", 1)diff --git a/products/ai_observability/backend/activity_logging.py b/products/ai_observability/backend/activity_logging.pyindex e1ab9928b7e7..b49c3d56dea7 100644--- a/products/ai_observability/backend/activity_logging.py+++ b/products/ai_observability/backend/activity_logging.py@@ -1,12 +1,39 @@import copy+import hashlibfrom typing import Any-from posthog.models.activity_logging.activity_log import Change, ChangeAction, Detail, changes_between, log_activity+from posthog.models.activity_logging.activity_log import (+ ActivityLog,+ Change,+ ChangeAction,+ Detail,+ changes_between,+ log_activity,+)from posthog.models.signals import model_activity_signal, mutable_receiverfrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.llm_prompt import LLMPromptLabel+ACTIVITY_LOG_ITEM_ID_MAX_LENGTH: int = ActivityLog._meta.get_field("item_id").max_length or 72+++def prompt_activity_item_id(prompt_name: str) -> str:+ """Deterministic activity-log key for a prompt, at most 72 chars (item_id is varchar(72)).++ Short names are used as-is. Longer names become a readable prefix plus a sha256 digest+ of the full name (128 bits kept), so a user cannot craft a second prompt name whose key+ collides with another prompt's. '#' cannot appear in a prompt name, so hashed keys can't+ collide with literal ones. The frontend does not mirror this: the History tab reads the+ key from the API (activity_item_id on the prompt serializer).+ """+ if len(prompt_name) <= ACTIVITY_LOG_ITEM_ID_MAX_LENGTH:+ return prompt_name+ digest = hashlib.sha256(prompt_name.encode("utf-8")).hexdigest()[:32]+ prefix = prompt_name[: ACTIVITY_LOG_ITEM_ID_MAX_LENGTH - 33]+ return f"{prefix}#{digest}"++# Lives here, not in api/evaluations.py, so it can wire at AppConfig.ready() without dragging the# evaluations viewset (which pulls scipy / google.genai / the ai_observability Temporal worker) onto# the django.setup() path. Evaluations are mutated outside web requests, so the audit log must@@ -86,7 +113,9 @@ def handle_llm_prompt_label_change(team_id=instance.team_id,user=user,was_impersonated=was_impersonated,- item_id=instance.id,+ # The prompt name, not the label row id: the History tab lists all label activity+ # for one prompt, and label rows are recreated on delete + re-add.+ item_id=prompt_activity_item_id(instance.prompt_name),scope="LLMPromptLabel",activity=activity,detail=Detail(diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 0c4a35abe8ba..ff6fc2e31d67 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -2157,6 +2157,8 @@ export interface LLMPromptListApi {readonly outline: readonly LLMPromptOutlineEntryApi[]/** Names of the labels currently pointing at this version. */readonly labels: readonly string[]+ /** Key for this prompt's rows in the activity log, e.g. for the History tab. Derived from the name, at most 72 characters. */+ readonly activity_item_id: stringreadonly prompt_preview: stringreadonly prompt_size_bytes: numberreadonly all_labels: readonly LLMPromptLabelSummaryApi[]@@ -2198,6 +2200,8 @@ export interface LLMPromptApi {readonly outline: readonly LLMPromptOutlineEntryApi[]/** Names of the labels currently pointing at this version. */readonly labels: readonly string[]+ /** Key for this prompt's rows in the activity log, e.g. for the History tab. Derived from the name, at most 72 characters. */+ readonly activity_item_id: string}export interface LLMPromptPublicApi {diff --git a/products/ai_observability/frontend/prompts/LLMPromptScene.tsx b/products/ai_observability/frontend/prompts/LLMPromptScene.tsxindex 81542fd206ae..1aa715fa705b 100644--- a/products/ai_observability/frontend/prompts/LLMPromptScene.tsx+++ b/products/ai_observability/frontend/prompts/LLMPromptScene.tsx@@ -6,16 +6,19 @@ import { IconPencil, IconPlay } from '@posthog/icons'import { LemonButton, LemonTabs } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { NotFound } from 'lib/components/NotFound'+import { FEATURE_FLAGS } from 'lib/constants'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, ActivityScope } from '~/types'import { PromptLogicProps, PromptMode, isPrompt, llmPromptLogic } from './llmPromptLogic'import {@@ -62,8 +65,15 @@ export function LLMPromptScene(): JSX.Element {isPromptFormDirty,} = useValues(llmPromptLogic)const { searchParams } = useValues(router)+ const { featureFlags } = useValues(featureFlagLogic)+ const labelsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_PROMPT_LABELS]const currentSearchParams = searchParams ?? {}- const activeViewTab = ['code', 'usage', 'experiments'].includes(searchParams?.tab) ? searchParams.tab : 'overview'+ // A ?tab= pointing at a tab that is not rendered (e.g. history with the flag off)+ // would leave LemonTabs with no matching content; fall back to overview instead.+ const availableViewTabs = labelsEnabled+ ? ['code', 'usage', 'experiments', 'history']+ : ['code', 'usage', 'experiments']+ const activeViewTab = availableViewTabs.includes(searchParams?.tab) ? searchParams.tab : 'overview'const {submitPromptForm,@@ -226,6 +236,20 @@ export function LLMPromptScene(): JSX.Element {label: 'Experiments',content: <PromptExperiments prompt={prompt} />,},+ ...(labelsEnabled+ ? [+ {+ key: 'history',+ label: 'History',+ content: (+ <ActivityLog+ scope={ActivityScope.LLM_PROMPT_LABEL}+ id={prompt.activity_item_id}+ />+ ),+ },+ ]+ : []),]}/>) : (diff --git a/products/ai_observability/frontend/prompts/LLMPromptsScene.stories.tsx b/products/ai_observability/frontend/prompts/LLMPromptsScene.stories.tsxindex a229e5492bd0..3a621c244afb 100644--- a/products/ai_observability/frontend/prompts/LLMPromptsScene.stories.tsx+++ b/products/ai_observability/frontend/prompts/LLMPromptsScene.stories.tsx@@ -30,6 +30,7 @@ function createMockPrompt(overrides: Partial<LLMPrompt> & { name: string }): LLMlatest_version: 1,version_count: 1,first_version_created_at: '2025-01-15T10:00:00Z',+ activity_item_id: overrides.name,...overrides,}}diff --git a/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsx b/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsxnew file mode 100644index 000000000000..ef0f8f98a85b--- /dev/null+++ b/products/ai_observability/frontend/prompts/promptLabelActivityDescriber.tsx@@ -0,0 +1,68 @@+import {+ ActivityLogItem,+ HumanizedChange,+ defaultDescriber,+ userNameForLogItem,+} from 'lib/components/ActivityLog/humanizeActivity'++// detail.name is "{prompt name}: {label name}" (set in backend activity_logging.py).+// The first ": " is always the separator: prompt names only allow [a-zA-Z0-9_-]+// (validate_prompt_name_value) and label names only allow lowercase [a-z0-9._-]+// (validate_prompt_label_name_value), so neither can contain a colon or a space.+function parseDetailName(logItem: ActivityLogItem): { promptName: string; labelName: string } {+ const name = logItem?.detail?.name ?? ''+ const separatorIndex = name.indexOf(': ')+ if (separatorIndex === -1) {+ return { promptName: '', labelName: name }+ }+ return { promptName: name.slice(0, separatorIndex), labelName: name.slice(separatorIndex + 2) }+}++export function promptLabelActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ const user = userNameForLogItem(logItem)+ const { promptName, labelName } = parseDetailName(logItem)+ const change = logItem.detail?.changes?.[0]+ const onPrompt = promptName ? (+ <>+ {' '}+ on prompt <b>{promptName}</b>+ </>+ ) : null++ if (logItem.activity === 'created') {+ return {+ description: (+ <>+ <strong className="ph-no-capture">{user}</strong> created label <b>{labelName}</b> pointing at{' '}+ <b>v{String(change?.after ?? '?')}</b>+ {onPrompt}+ </>+ ),+ }+ }++ if (logItem.activity === 'updated') {+ return {+ description: (+ <>+ <strong className="ph-no-capture">{user}</strong> moved label <b>{labelName}</b> from{' '}+ <b>v{String(change?.before ?? '?')}</b> to <b>v{String(change?.after ?? '?')}</b>+ {onPrompt}+ </>+ ),+ }+ }++ if (logItem.activity === 'deleted') {+ return {+ description: (+ <>+ <strong className="ph-no-capture">{user}</strong> removed label <b>{labelName}</b> (was pointing at{' '}+ <b>v{String(change?.before ?? '?')}</b>){onPrompt}+ </>+ ),+ }+ }++ return defaultDescriber(logItem, asNotification, labelName)+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 407bfb4f1c4a..7f93e7b4faf7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36207,6 +36207,8 @@ export namespace Schemas {readonly outline: readonly LLMPromptOutlineEntry[];/** Names of the labels currently pointing at this version. */readonly labels: readonly string[];+ /** Key for this prompt's rows in the activity log, e.g. for the History tab. Derived from the name, at most 72 characters. */+ readonly activity_item_id: string;}export interface LLMPromptDuplicate {@@ -36266,6 +36268,8 @@ export namespace Schemas {readonly outline: readonly LLMPromptOutlineEntry[];/** Names of the labels currently pointing at this version. */readonly labels: readonly string[];+ /** Key for this prompt's rows in the activity log, e.g. for the History tab. Derived from the name, at most 72 characters. */+ readonly activity_item_id: string;readonly prompt_preview: string;readonly prompt_size_bytes: number;readonly all_labels: readonly LLMPromptLabelSummary[];