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): activity-log prompt lifecycle events into the history tab (#73436)

Juraj Majerikc43608d8c047
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 8c030ce05167..d421c0766ecc 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2674,6 +2674,7 @@ const api = {
ActivityScope.COHORT,
ActivityScope.OAUTH_APPLICATION,
ActivityScope.EXTERNAL_DATA_SCHEMA,
+ ActivityScope.LLM_PROMPT,
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.tsx
index 7739225f1680..e760ff12aaf1 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/teamActivityDescribe
import { ActivityScope } from '~/types'
+import { promptActivityDescriber } from 'products/ai_observability/frontend/prompts/promptActivityDescriber'
import { promptLabelActivityDescriber } from 'products/ai_observability/frontend/prompts/promptLabelActivityDescriber'
import { alertConfigurationActivityDescriber } from 'products/alerts/frontend/components/activityDescriptions'
import { ticketActivityDescriber } from 'products/conversations/frontend/activityDescriber'
@@ -130,6 +131,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =
return ticketActivityDescriber
case ActivityScope.SIGNAL_SCOUT_CONFIG:
return signalScoutConfigActivityDescriber
+ case ActivityScope.LLM_PROMPT:
+ return promptActivityDescriber
case ActivityScope.LLM_PROMPT_LABEL:
return promptLabelActivityDescriber
default:
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fb367b0cdb69..7614f3a09bed 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5991,6 +5991,7 @@ export enum ActivityScope {
ENDPOINT_VERSION = 'EndpointVersion',
HEATMAP = 'Heatmap',
USER = 'User',
+ LLM_PROMPT = 'LLMPrompt',
LLM_PROMPT_LABEL = 'LLMPromptLabel',
LLM_TRACE = 'LLMTrace',
LOG = 'Log',
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index 2a59406f2e20..ece8a6046050 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -66,6 +66,7 @@ from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrot
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
+from products.ai_observability.backend.activity_logging import log_llm_prompt_activity
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outline
@@ -243,6 +244,12 @@ class LLMPromptViewSet(
def perform_create(self, serializer: BaseSerializer[Any]) -> None:
instance = cast(LLMPrompt, serializer.save())
+ log_llm_prompt_activity(
+ team=self.team,
+ user=cast(User, self.request.user),
+ prompt_name=instance.name,
+ activity="created",
+ )
report_user_action(
cast(User, self.request.user),
"llma prompt created",
@@ -403,7 +410,7 @@ class LLMPromptViewSet(
return auth_error
try:
- prompt_versions = archive_prompt(self.team, prompt_name)
+ prompt_versions = archive_prompt(self.team, prompt_name, user=cast(User, request.user))
except LLMPromptNotFoundError:
return self._prompt_not_found_response(prompt_name)
diff --git a/posthog/api/services/llm_prompt.py b/posthog/api/services/llm_prompt.py
index 6adc68bec0a5..de33b50b51d6 100644
--- a/posthog/api/services/llm_prompt.py
+++ b/posthog/api/services/llm_prompt.py
@@ -9,8 +9,10 @@ from django.db.models import QuerySet
from posthog.api.llm_prompt_serializers import MAX_PROMPT_PAYLOAD_BYTES
from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import Change
from posthog.storage.llm_prompt_cache import invalidate_prompt_latest_cache, invalidate_prompt_version_caches
+from products.ai_observability.backend.activity_logging import log_llm_prompt_activity
from products.ai_observability.backend.models.llm_prompt import (
LLMPrompt,
LLMPromptLabel,
@@ -207,6 +209,27 @@ def publish_prompt_version(
version_description=version_description,
)
+ changes = [
+ Change(
+ type="LLMPrompt",
+ action="changed",
+ field="version",
+ before=current_latest.version,
+ after=published_prompt.version,
+ )
+ ]
+ if version_description:
+ changes.append(
+ Change(type="LLMPrompt", action="created", field="version_description", after=version_description)
+ )
+ log_llm_prompt_activity(
+ team=team,
+ user=user,
+ prompt_name=prompt_name,
+ activity="published",
+ changes=changes,
+ )
+
refreshed_prompt = (
get_active_prompt_queryset(team).filter(pk=published_prompt.pk).order_by("-created_at", "-id").first()
)
@@ -262,11 +285,28 @@ def duplicate_prompt(
raise LLMPromptDuplicateNameConflictError() from err
raise
+ # One entry per prompt history: the copy records where it came from, the
+ # source records where it went.
+ log_llm_prompt_activity(
+ team=team,
+ user=user,
+ prompt_name=new_name,
+ activity="created",
+ changes=[Change(type="LLMPrompt", action="created", field="duplicated_from", after=source_name)],
+ )
+ log_llm_prompt_activity(
+ team=team,
+ user=user,
+ prompt_name=source_name,
+ activity="duplicated",
+ changes=[Change(type="LLMPrompt", action="created", field="duplicated_to", after=new_name)],
+ )
+
refreshed = get_active_prompt_queryset(team).filter(pk=new_prompt.pk).first()
return refreshed if refreshed is not None else new_prompt
-def archive_prompt(team: Team, prompt_name: str) -> list[int]:
+def archive_prompt(team: Team, prompt_name: str, *, user: User | None = None) -> list[int]:
with transaction.atomic():
prompt_versions = list(
LLMPrompt.objects.select_for_update()
@@ -285,6 +325,14 @@ def archive_prompt(team: Team, prompt_name: str) -> list[int]:
for label in LLMPromptLabel.objects.filter(team=team, prompt_name=prompt_name):
label.delete()
+ log_llm_prompt_activity(
+ team=team,
+ user=user,
+ prompt_name=prompt_name,
+ activity="archived",
+ changes=[Change(type="LLMPrompt", action="deleted", field="version_count", before=len(prompt_versions))],
+ )
+
def invalidate_caches_on_commit() -> None:
invalidate_prompt_latest_cache(team.id, prompt_name)
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index ce35d9dadd71..f822d6091278 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -949,6 +949,70 @@ class TestLLMPromptAPI(APIBaseTest):
assert response.json()["name"] == "archived-name"
assert response.json()["version"] == 1
+ def test_prompt_lifecycle_events_are_activity_logged_into_the_history_stream(self):
+ create = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "my-prompt", "prompt": "v1 content"},
+ format="json",
+ )
+ assert create.status_code == status.HTTP_201_CREATED
+ publish = self.client.patch(
+ f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/",
+ data={"prompt": "v2 content", "base_version": 1, "version_description": "tightened wording"},
+ format="json",
+ )
+ assert publish.status_code == status.HTTP_200_OK
+ label = self.client.put(
+ f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/labels/production/",
+ data={"version": 2},
+ format="json",
+ )
+ assert label.status_code == status.HTTP_201_CREATED
+ duplicate = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/duplicate/",
+ data={"new_name": "my-prompt-copy"},
+ format="json",
+ )
+ assert duplicate.status_code == status.HTTP_201_CREATED
+ archive = self.client.post(f"/api/environments/{self.team.id}/llm_prompts/name/my-prompt/archive/")
+ assert archive.status_code == status.HTTP_204_NO_CONTENT
+
+ entries = ActivityLog.objects.filter(team_id=self.team.id, scope="LLMPrompt")
+ assert sorted((entry.item_id, entry.activity) for entry in entries) == [
+ ("my-prompt", "archived"),
+ ("my-prompt", "created"),
+ ("my-prompt", "duplicated"),
+ ("my-prompt", "published"),
+ ("my-prompt-copy", "created"),
+ ]
+
+ published = entries.get(activity="published")
+ assert published.user is not None and published.user.id == self.user.id
+ published_detail = published.detail
+ assert published_detail is not None
+ assert published_detail["changes"][0]["field"] == "version"
+ assert published_detail["changes"][0]["before"] == 1
+ assert published_detail["changes"][0]["after"] == 2
+ assert published_detail["changes"][1]["field"] == "version_description"
+ assert published_detail["changes"][1]["after"] == "tightened wording"
+
+ copy_detail = entries.get(item_id="my-prompt-copy").detail
+ assert copy_detail is not None
+ assert copy_detail["changes"][0]["field"] == "duplicated_from"
+ assert copy_detail["changes"][0]["after"] == "my-prompt"
+
+ # The History tab queries both scopes by the shared item_id in one request;
+ # lifecycle and label entries must come back as one merged stream.
+ history = self.client.get(
+ f"/api/projects/{self.team.id}/activity_log/?scopes=LLMPrompt,LLMPromptLabel&item_id=my-prompt"
+ )
+ assert history.status_code == status.HTTP_200_OK
+ rows = history.json()["results"]
+ assert {row["scope"] for row in rows} == {"LLMPrompt", "LLMPromptLabel"}
+ # 4 lifecycle entries for my-prompt (the copy's "created" is keyed to the copy)
+ # + label created and label deleted-on-archive.
+ assert len(rows) == 6
+
class TestLLMPromptDuplicateSerializerValidationNoDB(SimpleTestCase):
# validate_new_name is a pure regex + reserved-name check (no context, no DB). The duplicate
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 9e5edb1829ca..372d36b7f0b3 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -80,6 +80,7 @@ ActivityScope = Literal[
"ExternalDataSource",
"ExternalDataSchema",
"Evaluation",
+ "LLMPrompt",
"LLMPromptLabel",
"LLMTrace",
"AIGatewayCredit",
diff --git a/products/ai_observability/backend/activity_logging.py b/products/ai_observability/backend/activity_logging.py
index b49c3d56dea7..a4d154eb1e80 100644
--- a/products/ai_observability/backend/activity_logging.py
+++ b/products/ai_observability/backend/activity_logging.py
@@ -1,6 +1,6 @@
import copy
import hashlib
-from typing import Any
+from typing import TYPE_CHECKING, Any
from posthog.models.activity_logging.activity_log import (
ActivityLog,
@@ -10,11 +10,15 @@ from posthog.models.activity_logging.activity_log import (
changes_between,
log_activity,
)
+from posthog.models.activity_logging.utils import activity_storage
from posthog.models.signals import model_activity_signal, mutable_receiver
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.llm_prompt import LLMPromptLabel
+if TYPE_CHECKING:
+ from posthog.models import Team, User
+
ACTIVITY_LOG_ITEM_ID_MAX_LENGTH: int = ActivityLog._meta.get_field("item_id").max_length or 72
@@ -34,6 +38,35 @@ def prompt_activity_item_id(prompt_name: str) -> str:
return f"{prefix}#{digest}"
+def log_llm_prompt_activity(
+ *,
+ team: "Team",
+ user: "User | None",
+ prompt_name: str,
+ activity: str,
+ changes: list[Change] | None = None,
+) -> None:
+ """Audit-log a prompt lifecycle event (create/publish/archive/duplicate).
+
+ Uses the same item_id as label activity so the prompt History tab gets both
+ streams in one query. Called explicitly from the prompt service functions —
+ LLMPrompt has no ModelActivityMixin because each row is a version, and a
+ per-row "created" entry per publish would say nothing about the lifecycle.
+ Impersonation comes from the request-scoped activity storage, same as the
+ mixin path.
+ """
+ log_activity(
+ organization_id=team.organization_id,
+ team_id=team.id,
+ user=user,
+ was_impersonated=activity_storage.get_was_impersonated(),
+ item_id=prompt_activity_item_id(prompt_name),
+ scope="LLMPrompt",
+ activity=activity,
+ detail=Detail(name=prompt_name, changes=changes),
+ )
+
+
# 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
diff --git a/products/ai_observability/frontend/prompts/LLMPromptScene.tsx b/products/ai_observability/frontend/prompts/LLMPromptScene.tsx
index 1aa715fa705b..c2607bc3d479 100644
--- a/products/ai_observability/frontend/prompts/LLMPromptScene.tsx
+++ b/products/ai_observability/frontend/prompts/LLMPromptScene.tsx
@@ -243,7 +243,7 @@ export function LLMPromptScene(): JSX.Element {
label: 'History',
content: (
<ActivityLog
- scope={ActivityScope.LLM_PROMPT_LABEL}
+ scope={[ActivityScope.LLM_PROMPT, ActivityScope.LLM_PROMPT_LABEL]}
id={prompt.activity_item_id}
/>
),
diff --git a/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx b/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx
new file mode 100644
index 000000000000..fd62a3719135
--- /dev/null
+++ b/products/ai_observability/frontend/prompts/promptActivityDescriber.tsx
@@ -0,0 +1,84 @@
+import {
+ ActivityLogItem,
+ HumanizedChange,
+ defaultDescriber,
+ userNameForLogItem,
+} from 'lib/components/ActivityLog/humanizeActivity'
+
+function changeAfter(logItem: ActivityLogItem, field: string): string | null {
+ const change = logItem.detail?.changes?.find((c) => c.field === field)
+ return change?.after != null ? String(change.after) : null
+}
+
+function changeBefore(logItem: ActivityLogItem, field: string): string | null {
+ const change = logItem.detail?.changes?.find((c) => c.field === field)
+ return change?.before != null ? String(change.before) : null
+}
+
+// Lifecycle events (create/publish/archive/duplicate) for scope LLMPrompt, written by
+// log_llm_prompt_activity in backend activity_logging.py. detail.name is the prompt name.
+export function promptActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
+ const user = userNameForLogItem(logItem)
+ const promptName = logItem?.detail?.name ?? ''
+
+ if (logItem.activity === 'created') {
+ const duplicatedFrom = changeAfter(logItem, 'duplicated_from')
+ return {
+ description: duplicatedFrom ? (
+ <>
+ <strong className="ph-no-capture">{user}</strong> created prompt <b>{promptName}</b> as a copy of{' '}
+ <b>{duplicatedFrom}</b>
+ </>
+ ) : (
+ <>
+ <strong className="ph-no-capture">{user}</strong> created prompt <b>{promptName}</b>
+ </>
+ ),
+ }
+ }
+
+ if (logItem.activity === 'published') {
+ const version = changeAfter(logItem, 'version')
+ const versionDescription = changeAfter(logItem, 'version_description')
+ return {
+ description: (
+ <>
+ <strong className="ph-no-capture">{user}</strong> published <b>v{version ?? '?'}</b> of prompt{' '}
+ <b>{promptName}</b>
+ {versionDescription ? <>: "{versionDescription}"</> : null}
+ </>
+ ),
+ }
+ }
+
+ if (logItem.activity === 'archived') {
+ const versionCount = changeBefore(logItem, 'version_count')
+ return {
+ description: (
+ <>
+ <strong className="ph-no-capture">{user}</strong> archived prompt <b>{promptName}</b>
+ {versionCount ? <> ({versionCount} versions)</> : null}
+ </>
+ ),
+ }
+ }
+
+ if (logItem.activity === 'duplicated') {
+ const duplicatedTo = changeAfter(logItem, 'duplicated_to')
+ return {
+ description: (
+ <>
+ <strong className="ph-no-capture">{user}</strong> duplicated prompt <b>{promptName}</b>
+ {duplicatedTo ? (
+ <>
+ {' '}
+ to <b>{duplicatedTo}</b>
+ </>
+ ) : null}
+ </>
+ ),
+ }
+ }
+
+ return defaultDescriber(logItem, asNotification, promptName)
+}
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 7b07492e450d..cb6df4606ceb 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1007,6 +1007,7 @@ export type ActivityLogListParams = {
* * `ExternalDataSource` - ExternalDataSource
* * `ExternalDataSchema` - ExternalDataSchema
* * `Evaluation` - Evaluation
+ * * `LLMPrompt` - LLMPrompt
* * `LLMPromptLabel` - LLMPromptLabel
* * `LLMTrace` - LLMTrace
* * `AIGatewayCredit` - AIGatewayCredit
@@ -1096,6 +1097,7 @@ export const ActivityLogListScope = {
ExternalDataSource: 'ExternalDataSource',
ExternalDataSchema: 'ExternalDataSchema',
Evaluation: 'Evaluation',
+ LLMPrompt: 'LLMPrompt',
LLMPromptLabel: 'LLMPromptLabel',
LLMTrace: 'LLMTrace',
AIGatewayCredit: 'AIGatewayCredit',
@@ -1172,6 +1174,7 @@ export const ActivityLogListScope = {
* * `ExternalDataSource` - ExternalDataSource
* * `ExternalDataSchema` - ExternalDataSchema
* * `Evaluation` - Evaluation
+ * * `LLMPrompt` - LLMPrompt
* * `LLMPromptLabel` - LLMPromptLabel
* * `LLMTrace` - LLMTrace
* * `AIGatewayCredit` - AIGatewayCredit
@@ -1249,6 +1252,7 @@ export const ActivityLogListScopesItem = {
ExternalDataSource: 'ExternalDataSource',
ExternalDataSchema: 'ExternalDataSchema',
Evaluation: 'Evaluation',
+ LLMPrompt: 'LLMPrompt',
LLMPromptLabel: 'LLMPromptLabel',
LLMTrace: 'LLMTrace',
AIGatewayCredit: 'AIGatewayCredit',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1e26656e3eeb..52e8b8f86b42 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -71788,6 +71788,7 @@ export namespace Schemas {
* * `ExternalDataSource` - ExternalDataSource
* * `ExternalDataSchema` - ExternalDataSchema
* * `Evaluation` - Evaluation
+ * * `LLMPrompt` - LLMPrompt
* * `LLMPromptLabel` - LLMPromptLabel
* * `LLMTrace` - LLMTrace
* * `AIGatewayCredit` - AIGatewayCredit
@@ -71878,6 +71879,7 @@ export namespace Schemas {
ExternalDataSource: 'ExternalDataSource',
ExternalDataSchema: 'ExternalDataSchema',
Evaluation: 'Evaluation',
+ LLMPrompt: 'LLMPrompt',
LLMPromptLabel: 'LLMPromptLabel',
LLMTrace: 'LLMTrace',
AIGatewayCredit: 'AIGatewayCredit',
@@ -71954,6 +71956,7 @@ export namespace Schemas {
* * `ExternalDataSource` - ExternalDataSource
* * `ExternalDataSchema` - ExternalDataSchema
* * `Evaluation` - Evaluation
+ * * `LLMPrompt` - LLMPrompt
* * `LLMPromptLabel` - LLMPromptLabel
* * `LLMTrace` - LLMTrace
* * `AIGatewayCredit` - AIGatewayCredit
@@ -72032,6 +72035,7 @@ export namespace Schemas {
ExternalDataSource: 'ExternalDataSource',
ExternalDataSchema: 'ExternalDataSchema',
Evaluation: 'Evaluation',
+ LLMPrompt: 'LLMPrompt',
LLMPromptLabel: 'LLMPromptLabel',
LLMTrace: 'LLMTrace',
AIGatewayCredit: 'AIGatewayCredit',